Click here to Skip to main content
12,886,393 members (43,488 online)
Rate this:
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.


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
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.
Kishor Deshpande 7-Feb-13 8:39am
My 5
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!
Ankur\m/ 7-Feb-13 9:10am
Thanks you!
manognya kota 7-Feb-13 9:16am
+5'ed !
Rate this: bad
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:

    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.
Rate this: bad
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
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)

    Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170424.1 | Last Updated 7 Feb 2013
Copyright © CodeProject, 1999-2017
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