1
String t = textBox1.Text;
         int a = int.Parse(t);
         if( a < 24)
         {
             MessageBox.Show("24 over.");
             textBox1.Clear();
         }

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format

How can I change String type value to integer type value?

3
  • 1
    What's in your textBox1.Text ? Commented Feb 23, 2015 at 0:59
  • The textBox1 is just input the number. Commented Feb 23, 2015 at 2:07
  • Ok, but what it contains, when you run your code? Commented Feb 23, 2015 at 2:08

2 Answers 2

0

t must be a string that's parseable to an integer. According to the runtime, it isn't.

You can make the code a bit more resilient by using TryParse instead. Something like this:

int a = 0;
if (!int.TryParse(t, out a))
{
    // input wasn't parseable to an integer, show a message perhaps?
}
// continue with your logic
Sign up to request clarification or add additional context in comments.

Comments

0

Short answer, use Binding

For building the example I'm going to assume Winforms as you haven't specified, but correct me if it's WPF instead. The basic principle is exactly the same anyway.

The idea is to bind a property to the control text, that will receive the parsed number directly from the control. Validation of correctness will be done by the binding engine and visual clues will be given in case of errors, and that property can the used safely in any further code.

An example implementation could be something like this:

//Declare property that will hold the converted value
public int TextBoxValue { get; set; }

protected override void OnLoad()
{
    //Initialize databinding from the control Text property to this form TextBoxValue property
    this.Textbox1.DataBindings.Add("Text",this,"TextBoxValue");
}

private void Button1_Click(object sender, EventArgs e)
{
     //This is an example of usage of the bound data, analogous to your original code
     //Data is read directly from the property
     if(this.TextBoxValue < 24)
     {
         MessageBox.Show("24 over.");
         //To move changes back, simply set the property and raise a PropertyChanged event to signal binding to update
         this.TextBoxValue = 0;
         this.PropertyChanged(this,new PropertyChangedEventArgs("TextBoxValue"));
     }
}

//Declare event for informing changes on bound properties, make sure the form implements INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;

That is, the code uses the property instead of the control directly, while the binding takes care of the conversions in between.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.