Textbox input range of numbers

2019-09-20 01:45发布

I'm trying to handle my textbox input values. I want the user to only be able to input numbers within a range using KeyPress. Ex. (0 - 1000). I have the code to prevent any input thats not a number. I can't quite figure out how to prevent the user from inputting a value thats not within a certain range.

Private Sub txt2x6LumberQuanity_KeyPress(sender As Object, e As KeyPressEventArgs) Handles   txt2x6LumberQuanity.KeyPress
    If Not Char.IsNumber(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
        e.Handled = True
    End If       
End Sub

Does anybody have any suggestions. I've spent a couple hours searching but can't seem to find the right solution.

2条回答
混吃等死
2楼-- · 2019-09-20 02:03

I would use the text changed and ErrorProvider component for this effect:

Valid Entry

OkValid

Invalid Entry

NotValid

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public int User2x6LumberQuantity
    {
        get
        {
            int x;
            if (int.TryParse(txt2x6LumberQuantity.Text, out x))
            {
                return x;
            }
            return 0;
        }
    }

    private void txt2x6LumberQuantity_TextChanged(object sender, EventArgs e)
    {
        errorProvider1.SetError(txt2x6LumberQuantity, null);
        int x=User2x6LumberQuantity;
        if (x<0||x>1000)
        {
            errorProvider1.SetError(txt2x6LumberQuantity, "Value Must Be (0-1000)");
            continueButton.Enabled=false;
        }
        else
        {
            continueButton.Enabled=true;
        }            
    }
}
查看更多
老娘就宠你
3楼-- · 2019-09-20 02:10

You could add this to the Keypress event handler

    If Char.IsNumber(e.KeyChar) Then
        Dim newtext As String = TextBox1.Text.Insert(TextBox1.SelectionStart, e.KeyChar.ToString)
        If Not IsNumeric(newtext) OrElse CInt(newtext) > 1000 OrElse CInt(newtext) < 0 Then e.Handled = True
    End If
查看更多
登录 后发表回答