Textbox input range of numbers

馋奶兔 提交于 2019-12-13 04:24:41

问题


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.


回答1:


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

Valid Entry

Invalid Entry

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;
        }            
    }
}



回答2:


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


来源:https://stackoverflow.com/questions/20448795/textbox-input-range-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!