locked
Input Errors RRS feed

  • Question

  • Hi,

    I am hoping some one can help me.  I am writing a code where I am using an input box to get values.  if the value is <= 0, I should get an error message indicating invalid number.  If the value is left blank or in a string format then I should get another input error message.  The first part of my code is working but If I leave the input field blank or input string I get an error message.  I am not sure what I am doing wrong.

    Here is my code:

     intProductNumber = int.Parse(Interaction.InputBox("Enter the Product Number"));
                try

                {        
                    if (intProductNumber <= 0)
                    {
                        MessageBox.Show("Invalid Product Number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message, ex.GetType().ToString());

    }

    Here are details of the exception message:

    System.FormatException
      HResult=0x80131537
      Message=Input string was not in a correct format.
      Source=mscorlib
      StackTrace:
       at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
       at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
       at System.Int32.Parse(String s)
       at test11.Form1.btnCreateStdSki_Click(Object sender, EventArgs e) in C:\Users\Manisha\source\repos\test11\Form1.cs:line 40
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at test11.Program.Main() in C:\Users\Manisha\source\repos\test11\Program.cs:line 19

      This exception was originally thrown at this call stack:
        [External Code]
        test11.Form1.btnCreateStdSki_Click(object, System.EventArgs) in Form1.cs
        [External Code]
        test11.Program.Main() in Program.cs


    Saturday, September 19, 2020 6:33 PM

Answers

  • The problem is that when the string returned from Interaction.InputBox is either empty or contains characters that cannot be converted to an integer value it will cause int.Parse() to throw the System.FormatException error that you have seen.  You can avoid the exception by calling int.TryParse() instead.

    For example -

    try
    {
        int intProductNumber = -1;
    
        bool bNumeric = int.TryParse(Interaction.InputBox("Enter the Product Number"), out intProductNumber);
        if (bNumeric && intProductNumber > 0)
        {
            // continue with valid product number
        }
        else
        {
            MessageBox.Show("Invalid Product Number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, ex.GetType().ToString());
    }


    Sunday, September 20, 2020 11:12 AM

All replies

  • I have no clue wtf an Interaction.InputBox is.  I mean I do, if you were posting to a VB forum, but you're in C#.  So I'm going to do you a favor and change that to a TextBox which actually makes some kind of sense.

            private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
            {
                // The smart way is to catch the KeyPress event
                if (!char.IsNumber(e.KeyChar))
                {
                    MessageBox.Show("Invalid Product Number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    // Setting e.Handled to true prevents the invalid input from entering the tbox at all
                    e.Handled = true;
                }
                else
                {
                    // Code for successful input
                }
            }
    
            private void textBox1_TextChanged(object sender, EventArgs e)
            {
                // Alternatively... if you want to annoy users by letting them enter 3 or 4 numbers and 
                // then accidentally hit a letter (or hold shift) and blank the whole box on any error...
                int testval = 0;
                // TryParse returns a boolean value indicating whether it was successful.
                // No need to try/catch/trap exceptions at all
                if (!int.TryParse(this.textBox1.Text, out testval))
                {
                    MessageBox.Show("Invalid Product Number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.textBox1.Text = string.Empty;
                }
                else
                {
                    // Code for successful input
                }
            }


    Before you can learn anything new you have to learn that there's stuff you don't know.

    Saturday, September 19, 2020 10:02 PM
  • The problem is that when the string returned from Interaction.InputBox is either empty or contains characters that cannot be converted to an integer value it will cause int.Parse() to throw the System.FormatException error that you have seen.  You can avoid the exception by calling int.TryParse() instead.

    For example -

    try
    {
        int intProductNumber = -1;
    
        bool bNumeric = int.TryParse(Interaction.InputBox("Enter the Product Number"), out intProductNumber);
        if (bNumeric && intProductNumber > 0)
        {
            // continue with valid product number
        }
        else
        {
            MessageBox.Show("Invalid Product Number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, ex.GetType().ToString());
    }


    Sunday, September 20, 2020 11:12 AM
  • HI RLWA32,

    Thank you for your solution.  I tried it.

    I had to make a slight change and it worked

    your solution had a statement the if (bNumeric && intProductNumber > 0)

    but I changed it to if (bNumeric || intProductNumber <= 0). it seem to work

    Thank you so much.  you have provided me insight on a different way of looking at solution.

    Friday, September 25, 2020 12:46 AM
  • Hi,

    Thank you for your help.  I am actually using C#.  In Windows form, interaction input box pops up when the user clicks a button. The user can enter information as per the interaction box question. 


    Friday, September 25, 2020 12:55 AM
  • I think you misunderstood something about the code I posted.

    In your initial post you wrote "if the value is <= 0, I should get an error message indicating invalid number.  If the value is left blank or in a string format then I should get another input error message."

    So this code will produce an error message if the value returned from Interaction.InputBox cannot be converted to a numeric value.  If it can be converted to a numeric value then that value must be greater than 0 to be a valid account number.  That is the specification that you set forth.

        bool bNumeric = int.TryParse(Interaction.InputBox("Enter the Product Number"), out intProductNumber);
        if (bNumeric && intProductNumber > 0)
        {
            // continue with valid product number
        }
        else
        {
            MessageBox.Show("Invalid Product Number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    

    Your suggested change to

    if (bNumeric || intProductNumber <= 0)
    will accept any numeric value returned by Interaction.Inputbox, including invalid account numbers (0 or negative values).

    Friday, September 25, 2020 1:43 AM