Parth6792
Parth6792

Reputation: 13

Convert string to int datatype in c# .net

I am working with Microsoft SQL Server Management Studio, and C# .net

My code fetches string data from the webBrowser, stores it in a textbox, compares it with values in my database, and gets the corresponding int ID to that string. Now, this int ID is displayed in a textbox (optional), and is then stored in another table in my database.

My code is as follows:

string p = dComm.executeScalar("select StateID from StateMaster where StateCode='" + txtState.Text + "'");
textBox1.Text = p;
Convert.ToInt32(p);

This fetches the StateID, and displays it in a textbox. I then open another table from the database, and put the value as shown below.

dTbl = dComm.openDataTable("CompanyMaster", "select * from CompanyMaster where 1=0 ");
DataRow dRow;
dRow = dTbl.NewRow();
dRow["StateID"] = p;

Now, this code works perfectly fine when i run the code on the HTML file of the page, but if I try to run it directly from the web browser, it gives an error

Input String was not in a correct format

The error is shown at the line:

Convert.ToInt32(p);

Am I missing something? Can anyone help me with this?

Upvotes: 1

Views: 4687

Answers (2)

Jim
Jim

Reputation: 6881

Try using Int32.Parse(p) instead. You can also use the TryParse if you don't want an exception on a failed parse, and instead you would get a bool that shows whether it was successful or not.

So from your example, it would be like this...

string p = dComm.executeScalar("select StateID from StateMaster where StateCode='" + txtState.Text + "'");
textBox1.Text = p;
int pInt = Int32.Parse(p);

Or if you want to use TryParse, it would be like this...

string p = dComm.executeScalar("select StateID from StateMaster where StateCode='" + txtState.Text + "'");
textBox1.Text = p;
int pInt;
if(!Int32.TryParse(p, out pInt))
{
  //Parsing failed, do something about it
}

Upvotes: 0

Philip Gullick
Philip Gullick

Reputation: 995

The problem you are having:

Convert.To is relatively hard work, and shouldn't (in my eyes) be used when the input can come from the end user. When bad data is provided to the Convert.To it gives exceptions that cannot be handled very well.

For example:

 textbox1.Text = "test";
 Convert.ToInt32(textbox1.text);

It will crash and burn.

I would advise you get into the routine of using TryParse, which handles bad values much better.

Example:

int test = 0;
int.TryParse(textbox1.text, out test)
{
      //do validation with if statements
}

This would cancel out any bad data, and also ensure that the end user would only get user friendly message boxes that you have wrote yourself. Meaning you can tell them where they have put in a bad value so that they can correct it without the program crashing and burning.

Upvotes: 1

Related Questions