Alex Moreno
Alex Moreno

Reputation: 138

Converting String to Int C#

I am trying to convert an inputted string to an int. I have tried int.parse, and int.parse32 but when I press "enter" I get the following error:

System.FormatException: Input string was not in a correct format.
  at System.Number.StringToNumber(String str, NumberStyles options, 
                                  NumberBuffer & number...."

partial class Form1:

this.orderID.Text = currentID;
this.orderID.KeyPress += new KeyPressEventHandler(EnterKey);

partial class Form1:Form:

  public int newCurrentID;
  private void EnterKey(object o, KeyPressEventArgs e)
    {
        if(e.KeyChar == (char)Keys.Enter)
        {
            try
            {
                newCurrentID = int.Parse(currentID);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            e.Handled = true;
        }
    }

Upvotes: 1

Views: 778

Answers (4)

Magnus
Magnus

Reputation: 46909

String is immutable so when you assign currentID to the textbox any changes of that text will not be reflected in the variable currentID

this.orderID.Text = currentID;

What you need to do in the EnterKey function is to use the Textbox value directly:

private void EnterKey(object o, KeyPressEventArgs e)
{
        if(e.KeyChar == (char)Keys.Enter)
        { 
            if(!int.TryParse(orderID.Text, out newCurrentID))
               MessageBox.Show("Not a number");
            e.Handled = true;
        }
 }

Upvotes: 4

Neeraj
Neeraj

Reputation: 4489

Try This Code

if (!string.IsNullOrEmpty(currentID)){
     newCurrentID = int.Parse(currentID);
}

Upvotes: 0

Kai
Kai

Reputation: 2013

Use TryParse instead of parse the value directly:

int intResult = 0;

if (Int32.TryParse(yourString, out intResult) == true)
{
    // do whatever you want...
}

Upvotes: 1

Hikiko
Hikiko

Reputation: 309

Check string for string.IsNullOrEmpty() and do not try to parse such strings.

Upvotes: 4

Related Questions