Click here to Skip to main content
15,902,901 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C# winform textbox, I have a textbox and want to enter decimals like .2 or .7.
I keep getting System.FormatException: 'Input string was not in a correct format.

C#
<pre> private void tb_Percentage_TextChanged(object sender, EventArgs e)
        {
           
            for (int i = 0; i < dataGridView1.Rows.Count; i++)

            {
                DataGridViewRow row = dataGridView1.Rows[i];
             
              decimal d = Convert.ToDecimal(dataGridView1.Rows[i].Cells[31].Value);
              //  tb_Percentage.Text = string.Format("{0:C2}", Convert.ToInt32(tb_Percentage.Text));
                decimal E = decimal.Parse(tb_Percentage.Text);
                decimal f = d * E;
                dataGridView1.Rows[i].Cells[32].Value = f.ToString("#.00");
                           
            }
        }


What I have tried:

//  tb_Percentage.Text = string.Format("{0:C2}", Convert.ToInt32(tb_Percentage.Text));


also tried Regular-Expressions
Posted
Updated 6-Mar-20 10:19am

When trying to convert text to a number you will be better off using TryParse methods as you can determine if the conversion failed and take the appropriate action.

eg:
if (decimal.TryParse(stringvalue, out decimal myresult))
{
    // valid conversion comes here
    // myresult will contain a valid number on parse success
}
else
{
    // failed conversion comes here
    // myresult will be zero on parse failure
}
 
Share this answer
 
v2
Reading through the MS documentation and samples...
Convert Class (System) | Microsoft Docs[^]
FormatException
This occurs when the attempt to convert a string value to any other base type fails because the string is not in the proper format. The exception is thrown for the following conversions:
1. A string to be converted to a Boolean value does not equal Boolean.TrueString or Boolean.FalseString.
2. A string to be converted to a Char value consists of multiple characters.
3. A string to be converted to any numeric type is not recognized as a valid number
And if we look at the code block up the page, for the attempt to convert to Int
C#
int newInteger = 0;
try {
	System.Console.WriteLine("Enter an integer:");
	newInteger = System.Convert.ToInt32(System.Console.ReadLine());
}
//catch (System.ArgumentNullException) { ... }

catch (System.FormatException) {
  System.Console.WriteLine(

    "String does not consist of an optional sign followed by a series of digits."

  );
} 
//catch (System.OverflowException) {... }
"String does not consist of an optional sign followed by a series of digits."
It would appear that the only thing that may start a number is either a sign (for positive or negative) or a number.
The values you were provided in your question began with a decimal point, which may be why you are failing.

According to a couple of resources, the correct notation for a decimal value less than 1 is to begin with a "0" before the decimal point. I never really thought about it.
Numbers - Decimal Numbers - In Depth[^]
Writing a Decimal Number Less Than 1 Given its Name - Tutorialspoint[^]

Now that we know all of this... what should I do?
As the other answer states, you may want to try using the TryParse method
C#
decimal d = 0;
if (!Decimal.TryParse(dataGridView1.Rows[i].Cells[31].Value, out d) {
	// Parsing failed !
	// handle appropriately
} 
Decimal.TryParse Method (System) | Microsoft Docs[^]

Another option would be to check the string first to see if the first character is a decimal point; and if so, prepend it with a "0"
C#
//decimal d = Convert.ToDecimal(dataGridView1.Rows[i].Cells[31].Value);
string Cell31 = dataGridView1.Rows[i].Cells[31].Value;
if (Cell31.Substring(0,1) == ".") { Cell31 = "0" + Cell31; }
decimal d = Convert.ToDecimal(Cell31);
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900