0

I've found different help through this website but still can't seem to convert a string to int. I've tried many different ways. Here are two of them. On button_click I need to read the textboxes and convert them to int so I can perform standard logic on them. (a > b functions). Below the first section is what I'm using to force the use of numbers during entry into the text boxes.

    private void write_button_Click(object sender, EventArgs e)
       {
        int mat_od1 = int.Parse(matod_box.Text); //Input string in wrong format.
        int mat_id1 = int.Parse(matid_box.Text);
        int fod1 = int.Parse(fod_box.Text);
        int fid1 = int.Parse(fid_box.Text);
        int hp1 = int.Parse(hp_box.Text);

        //This next section is just to show something else I've tried.

        decimal mat_od = Convert.ToDecimal(matod_box.Text); //Same error.
        decimal mat_id = Convert.ToDecimal(matid_box.Text);
        decimal fod = Convert.ToDecimal(fod_box.Text);
        decimal fid = Convert.ToDecimal(fid_box.Text);
        decimal hp = Convert.ToDecimal(hp_box.Text);
        decimal pass_od = mat_od;

    }

       private void fod_box_TextChanged(object sender, EventArgs e)
    {
        try
        {
            int numinput = int.Parse(fod_box.Text);
            if (numinput < 1 || numinput > 500)
            {
                MessageBox.Show("You must enter a number between 0 and 500.");
            }
        }
        catch (FormatException)
        {

            MessageBox.Show("You need to enter a number.");
            fod_box.Clear();

        }

Any help would be appreciated.

marcmiller2007
  • 119
  • 2
  • 10
  • try setting a break point on your first **int.parse** statement. See what the value of **matod_box.Text** is. – Mark May 25 '12 at 14:56
  • 1
    If you have these numeric textboxes in several places, you should consider making a user control, inherit textbox and add validation. – Yatrix May 25 '12 at 15:05
  • I do have multiple boxes so good point. – marcmiller2007 May 25 '12 at 15:13
  • Possible duplicate of [How do I make a textbox that only accepts numbers?](https://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers) –  Jul 20 '18 at 19:41

4 Answers4

4

instead of int.Parse() you should use int.TryParse(string,out int)
this way you would be able to chek the output and decide wether the string was correctly parsed or not

int i;string s="";
if(int.TryParse(s,out i))
{
 //use i
}
else
{
//show error
}
Parv Sharma
  • 12,581
  • 4
  • 48
  • 80
2

The int.parse conversion should work, as in this sample:

  string s = "111";
  int i;
  if (int.TryParse(s, out i))
  {
     Console.Write(i);
  }
  else
  {
      Console.Write("conversion failed");
  }

Are you sure you actually provide legal input for your ints? In any case, you should use TryParse like I did in my sample. Theres no need to use try..catch where you can use boolean methods provided by the framework, which will get you the same result..

YavgenyP
  • 2,113
  • 14
  • 11
  • 1
    Adding to YavgenyP's point, try..catch is a lot slower than Boolean comparisons. Exceptions throw the processing flow all out of whack! Avoid them if you can. – Mark May 25 '12 at 14:58
  • @Mark. It would be more accurate to say exceptions should be exceptional, so what you shouldn't do is use them for non-exceptional processing such as the text box has nowt in it. – Tony Hopkinson May 25 '12 at 15:08
1

All depends on what you are allowing to be put in the text box.

If it might not be a string that can be converted to an integer, including blank, then something like

int value;
if (int.TryParse(SomeString, out value)
{
   // it is an int
}
else
{
  // it's not an int, so do nothing raise a message or some such.
}
Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39
0

In addition to using Int32.TryParse in the button Click event handler as others have pointed out, you need to be careful what you're doing in the TextBox Changed event handler. You're code here is flawed:

private void fod_box_TextChanged(object sender, EventArgs e) 
{ 
    try 
    { 
        int numinput = int.Parse(fod_box.Text); 
        ...
    } 
    catch (FormatException) 
    { 
        MessageBox.Show("You need to enter a number.");  
        fod_box.Clear(); 
    } 

Calling foo_box.Clear() will clear any text from the textbox, calling the TextChanged handler to be executed again (unless the TextBox was already empty). So if you enter a non-numeric value, your message box will be displayed twice - the first time when it attempts to parse your non-numeric value, the second time when it attempts to parse an empty string as a result of the call to Clear().

In general, I'd avoid doing validation in the Changed event handler.

Joe
  • 122,218
  • 32
  • 205
  • 338
  • Isn't there an Handled property on the EventArgs object that he can use if it's a non-number? – Yatrix May 25 '12 at 15:11
  • Thanks for the help! tryparse is working and Joe you are correct. The box does get displayed twice. whether I have the clear function or not because of the textchanged event. – marcmiller2007 May 25 '12 at 15:13
  • "The box does get displayed twice. whether I have the clear function or not because of the textchanged " - you can get rid of this by explicitly allowing an empty string. – Joe May 25 '12 at 16:51