1

I'm accepting a string value from the user via a text box in a form. It is then used in a query against a database table and although it is a string, I require the only characters entered to be whole numbers.

I've tried various methods, such as the INT32 and TryParse functions. However, I run into issues when attempting an IF ELSE or TRY CATCH to prevent anything from executing until the input is 'acceptable'.

What is the easiest way to allow whole numbers only to be entered into the text box, or to identify anything but whole numbers and fail the execution?

5 Answers 5

3

Yes, you can use int.TryParse:

string selectSql = "SELECT * FROM SomeTable WHERE ID = @ID";

int id;
if (!int.TryParse(txtID.Text, out id))
    MessageBox.Show("ID must be an integer.");
else
{
    using (var myCon = new SqlConnection(connectionString))
    using (var selectCommand = new SqlCommand(selectSql, myCon))
    {
        selectCommand.Parameters.AddWithValue("@ID", id);
        myCon.Open();
        using (var reader = selectCommand.ExecuteReader())
        {
            // do something with the records
        }
    }
}

You can also use a NumericUpDown control.

Sign up to request clarification or add additional context in comments.

Comments

1

Use a NumericUpDown control instead of a TextBox

1 Comment

The NumericUpDown allows other characters, such as ,.-
1

I know of 3 possible ways to do it:

  1. Remove invalid characters in TextChanged event of your textbox:

    private void txb_TextChanged(object sender, EventArgs e)
    {
    int selStart = txb.SelectionStart;
    
    string result = txb.Text;
    
    // remove all that aren't digits
    result = Regex.Replace(result, @"[^0-9]", string.Empty);
    
    txb.Text = result;
    
    // move cursor
    if (selStart > txb.Text.Length)
        txb.Select(txb.Text.Length, 0);
    else txb.Select(selStart, 0);
    }
    
  2. Extend TextBox control and ignore all invalid keys that user presses

    public class IntegerTextBox : TextBox
    {
    private Keys[] int_allowed = {
             Keys.D1,
             Keys.D2,
             Keys.D3,
             Keys.D4,
             Keys.D5,
             Keys.D6,
             Keys.D7,
             Keys.D8,
             Keys.D9,
             Keys.D0,
             Keys.NumPad0,
             Keys.NumPad1,
             Keys.NumPad2,
             Keys.NumPad3,
             Keys.NumPad4,
             Keys.NumPad5,
             Keys.NumPad6,
             Keys.NumPad7,
             Keys.NumPad8,
             Keys.NumPad9,
             Keys.Back,
             Keys.Delete,
             Keys.Tab,
             Keys.Enter,
             Keys.Up,
             Keys.Down,
             Keys.Left,
             Keys.Right
        };
     protected override void OnKeyDown(KeyEventArgs e)
            {
                base.OnKeyDown(e);
                if (e.Modifiers == Keys.Control) return;
    
                if (!int_allowed.Contains(e.KeyCode))
                {
                    e.SuppressKeyPress = true;
                }
            }
        }
    }
    
  3. process KeyDown and/or KeyPress event and cancel it if somthing that isn't allowed was pressed

Comments

0

You can write your own class that inherits from TextBox:

    public class NumericTextBox : TextBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        base.OnKeyPress(e);

        var key = e.KeyChar + "";
        if (key == "\b")
            return;
        double number;
        string newText = Text.Remove(SelectionStart, SelectionLength).Insert(SelectionStart, key);
        if (newText.Length == 1 && key == "-")
            return;
        if (!double.TryParse(newText, NumberStyles.Float, CultureInfo.InvariantCulture, out number))
        {
            e.Handled = true;
        }
    }

    public double Value
    {
        get { return Text.Length == 0 ? 0 : double.Parse(Text, CultureInfo.InvariantCulture); }
    }
}

Comments

0

Just as another alternative you could use the textboxes TextChanged event.

int.TryParse the text everytime the value is changed, if it doesn't work just clear the textbox (or keep the last value that worked and revert to that on fail).

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.