Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
From the following code,

C#
string strid  = txtId.Text;
int id = Convert.ToInt32(strid);


I was getting a message like this
"Input string was not in a correct format"
what should I do?
Posted
Updated 9-Jul-15 2:42am
v2
Comments
[no name] 9-Jul-15 8:36am    
Supply a string in the correct format, of course.
CB Sharma 9-Jul-15 8:37am    
strid valus is not integer type that's why you got error message "Input string was not in a correct format"

Check strid value in debug mode. You find answer of this error.

Try this,

C#
string strid  = txtId.Text;
int id=0;
Int32.TryParse(strid, out id);


Using above code, you'll not get the error, and you'll get the converted value in id variable.If strid is not in well formed input, you'll get 0 in id as a value.:-)
 
Share this answer
 
Comments
Mani Kandan 9-Jul-15 8:51am    
tanq
Akhil Mittal 9-Jul-15 8:53am    
Mark it as an answer if it works :-)
Krunal Rohit 9-Jul-15 9:00am    
Answer should be accepted.

-KR
Whatever is in txtId.Text can't be interpreted as an int. You can't control what is in a textbox so use int.TryParse instead so that you can handle when the input is not an int.
 
Share this answer
 
Hi,

Check if txtId.Text has value. If txtId.Text is ""(empty), then how it convert to integer?

so, your code should be as follow:

C#
string strid = txtId.Text;

if(strid != "")
{
    int id = Convert.ToInt32(strid);
}
 
Share this answer
 
Comments
Akhil Mittal 9-Jul-15 8:49am    
This can not be the solution, It is not necessary that because of empty value of string this error is coming.This error is coming because Convert.Itn32 is getting string that can not be converted to integer, something that is not numeric in nature.It has to be resolved by Int32.TryParse.
[no name] 9-Jul-15 9:08am    
Actually he is right, sort of. The implementation is not what I would choose but an empty string will throw that exception.
Mani Kandan 9-Jul-15 11:49am    
Actually, there is a value inside the cells

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