Bio Salibio
Bio Salibio

Reputation: 19

Input string was not in a correct format C#

enter image description here

   private void textquantity_TextChanged(object sender, EventArgs e)
    {
        string lowitem = "lowitem";  
        string highitem = "highitem";  

        if (Convert.ToInt32(textquantity.Text) <= 5)   
            texthilow.Text = lowitem;   
        else  
            texthilow.Text = highitem;   

    }

i always get an error on

if (Convert.ToInt32(textquantity.Text) <= 5)  

Upvotes: 0

Views: 817

Answers (2)

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14624

Please check if your textbox has empty value it will not convert to int.

As you are getting value in TextChanged event so when you press backspace and there is no value in it, it will throw exception.

if(!string.IsNullOrEmpty(textquantity.Text))
{
int quantity;
if (int.TryParse(textquantity.Text, out quantity))   
        texthilow.Text = quantity.ToString();   
    else  
        texthilow.Text = quantity.ToString();   
}

Also try to use int.TryParse because it will not throw exception if string is not a valid int.

Upvotes: 6

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

Try using TryParse instead of Parse:

  int value;

  if (int.TryParse(textquantity.Text, out value))  
    if (value <= 5)   
      texthilow.Text = lowitem; 
    else  
      texthilow.Text = highitem; 
  else {
    // textquantity.Text contains an invalid value, e.g. "bla-bla-bla"
  }

Upvotes: 4

Related Questions