Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# ASP.NET
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 7-Feb-13 2:19am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Use Int32.TryParse Method[^]
bool success = Int32.TryParse(textbox1.Text, out a);
a will contain 0, if the conversion was unsuccessful.
  Permalink  
Comments
Kishor Deshpande at 7-Feb-13 8:39am
   
My 5
Ankur\m/ at 7-Feb-13 9:10am
   
Thanks you!
Zoltán Zörgő at 7-Feb-13 8:52am
   
That's the way, +5!
Ankur\m/ at 7-Feb-13 9:06am
   
Thanks for the vote!
manognya kota at 7-Feb-13 9:16am
   
+5'ed !
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

Another solution for this is to just have a check and see if your textbox is empty:
 
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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

hi all,
 
int? lat1 = string.IsNullOrEmpty(txtempid.Text) ? (int?)null : Convert.ToInt32(txtempid.Text);
          int empid = Convert.ToInt32(lat1);
 
this code working fine
  Permalink  
Comments
Pete O'Hanlon at 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)

  Print Answers RSS
0 mhegazy94 460
1 Sergey Alexandrovich Kryukov 405
2 Kornfeld Eliyahu Peter 285
3 Gihan Liyanage 167
4 Sibeesh KV 150
0 Sergey Alexandrovich Kryukov 6,805
1 OriginalGriff 6,696
2 CPallini 5,350
3 George Jonsson 3,609
4 Gihan Liyanage 2,792


Advertise | Privacy | Mobile
Web01 | 2.8.140922.1 | Last Updated 7 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100