Click here to Skip to main content
15,886,592 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have two textBoxs and one button, textbox1 is ascept Number and textbox2 is convert them in Words. when i click button1 as a clear the field it shows the error-

Input string was not in a correct format

error dialogbox shows here error-
string word = ConvertNumbertoWords(Convert.ToInt32(txtamount.Text));


What I have tried:

private void buttonClear_Click(object sender, EventArgs e)
{

textBox1.Text = String.Empty;
txtsrno.Text = String.Empty;
txtdescription.Text = String.Empty;
txtquantity.Text = String.Empty;
txtrate.Text = String.Empty;
comboBox1.Text = String.Empty;
txtamount.Text = String.Empty;
txtword.Text = String.Empty;

string word = ConvertNumbertoWords(Convert.ToInt32(txtamount.Text));
txtword.Text = word;

}




string word = ConvertNumbertoWords(Convert.ToInt32(txtamount.Text));
Posted
Updated 11-Dec-18 20:25pm

1 solution

An empty string is not a valid integer representation, yet you ask Convert.ToInt32 to produce an integer from it... that does not make it happy.

Of course, they could have implemented Convert.ToInt32 so it returns 42 when it gets a string that isn't representing an integer - a completely reasonable decision if you ask me. But they decided to let it fail instead. Maybe because someone else might have expected it to return 0, -1, int.MinValue or some other arbitrary integer.


You can use int.TryParse(string s) to avoid the error being thrown as an exception and handle it yourself. If you want the empty string to be treated like "42", then write some code that sets the value 42 instead of calling Convert.ToInt32 if the string is null or empty (use string.IsNullOrEmpty).
 
Share this answer
 
v2
Comments
Member 14083059 12-Dec-18 4:02am    
thanxx @Imoelleb

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