Click here to Skip to main content
15,885,032 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I have two textboxes.

how to convert empty string to int
my code like this.


textbox1.Text="";

int a= convert.ToInt32(textbox1.Text);
i got the error

Input string was not in a correct format.
int a = Convert.ToInt32(textbox1.Text);
Posted

Use Int32.TryParse Method[^]
C#
bool success = Int32.TryParse(textbox1.Text, out a);

a will contain 0, if the conversion was unsuccessful.
 
Share this answer
 
Comments
Kishor Deshpande 7-Feb-13 8:39am    
My 5
Ankur\m/ 7-Feb-13 9:10am    
Thanks you!
Zoltán Zörgő 7-Feb-13 8:52am    
That's the way, +5!
Ankur\m/ 7-Feb-13 9:06am    
Thanks for the vote!
manognya kota 7-Feb-13 9:16am    
+5'ed !
Another solution for this is to just have a check and see if your textbox is empty:

C#
if(textBox1.Text.Equals(""))
{
    int a = 0;
}


Also later on you have to use regular expressions to check if the input box contains anything other than numbers. If it doesn't then convert it to integer straight away, otherwise display an error.
 
Share this answer
 
hi all,

C#
int? lat1 = string.IsNullOrEmpty(txtempid.Text) ? (int?)null : Convert.ToInt32(txtempid.Text);
          int empid = Convert.ToInt32(lat1);


this code working fine
 
Share this answer
 
Comments
Pete O'Hanlon 7-Feb-13 8:53am    
Wow. There's so much wrong with this solution I don't know where to start. Ok, first of all, don't use Convert.ToInt32 - what happens if the user has typed 1.2 in the text box? Secondly, why cast to (int?) null when you could just have put 0 in there and removed the nullable int? Finally - and most importantly, TryParse sets the output to 0 if it's an invalid value in there.

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