TerryTheTerminator
TerryTheTerminator

Reputation: 23

ASP.net Converting inputbox string to integer?

I have been trying for ages to convert a string taken from an input box in my asp form and converting it to an integer.

This integer variable will then be used for a database operation I have planned.

Here is what I have tryed:

 string mytxtCHI = txtID.Text;
            int @CHI = Convert.ToInt16(mytxtCHI);

Error:

System.FormatException {"Input string was not in a correct format."}

Things I have tried:

-  string mytxtCHI = txtID.Text;
            int myNewID=(Int32.Parse(txtID.Text));

Thankyou for your time :)

Upvotes: 1

Views: 5705

Answers (5)

Senad Meškin
Senad Meškin

Reputation: 13756

Your way is correct, but what you should do to avoid errors

int myNewID = 0;

    if(int.TryParse(txtID.Text, out myNewID))
     {
        //your code here
    }
    else
    {
       //your error handling here
    }

Upvotes: 1

James McCormack
James McCormack

Reputation: 9954

Put a breakpoint on the line in Visual Studio. In debug mode, run to the breakpoint, and hover over txtID.Text to see what's in it.

When in the page lifecycle are you checking this value? Check it after Page Init. Check HttpRequest.Form to see what came down the wire.

Upvotes: 1

hungryMind
hungryMind

Reputation: 6999

Use watch window or System.Diagnostics.Debug.WriteLine(mytxtCHI) to check what's the value you are passing, is it blank?

Upvotes: 0

Jim Mischel
Jim Mischel

Reputation: 134005

You should use Int.TryParse, and handle the case when the value isn't a valid integer.

string mytxtCHI = txtId.Text;
int val;
if (!int.TryParse(mytxtCHI, out val))
{
    // error here, value was not a valid integer.
}
// here, val contains the value, expressed as an integer.

Upvotes: 0

Peter
Peter

Reputation: 27944

You should use tryparse:

  string mytxtCHI = txtID.Text;
  int number;
  bool result = Int32.TryParse(mytxtCHI , out number);
  if (result)
  {
     Console.WriteLine("Converted '{0}' to {1}.", mytxtCHI , number);         
  }
  else
  {
     if (value == null) value = ""; 
     Console.WriteLine("Attempted conversion of '{0}' failed.", mytxtCHI );
  }

Upvotes: 1

Related Questions