Click here to Skip to main content
15,889,861 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
System.FormatException: 'Input string was not in a correct format.'


when i click button itz showing this error . i want to increment textbox3.Text on each button click

What I have tried:

<pre>foreach (string i in listBox1.Items)
                        {
                            if (i == content)
                            {
                                MessageBox.Show("already there");
                                isValid = false;
                                textBox3.Text = "0";
                            }
                            
                        }
                        if (isValid)
                        {
                            listBox1.Items.Add(content);
                            a = Convert.ToInt32(content.ToString());
                            a++;
                            textBox3.Text = a.ToString();
                            
                        }
Posted
Updated 24-May-21 1:08am
Comments
Richard MacCutchan 24-May-21 6:09am    
Use the debugger to see what is returned by content.ToString().
BillWoodruff 25-May-21 10:54am    
your code makes no sense: you are iterating the ListBox Items, and, at the same time, adding new Items: that's an error right there.

1 solution

C#
a = Convert.ToInt32(content.ToString());

Mostly you are trying to convert an empty string or a string which is not an integer.

Quote:
A FormatException exception can be thrown for one of the following reasons:

- In a call to a method that converts a string to some other data type, the string doesn't conform to the required pattern.
- A type implements the IFormattable interface, which supports format strings that define how an object is converted to its string representation, and an invalid format string is used.
For more details, refer: FormatException Class (System) | Microsoft Docs[^]
 
Share this answer
 
Comments
BillWoodruff 25-May-21 10:53am    
this type of answer in response to a code sample that is clearly messed up ... ridiculous !

the code is iterating the ListBox Items, and, at the same time, adding new Items.

do you really think explaining the error message is relevant ?

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