Numeric TextBox

后端 未结 13 1091
再見小時候
再見小時候 2020-12-03 20:01

Im new to programming and I dont know very much about but I\'m making a calculator, and i want to use a textbox that only acepts numbers and decimals, and when the user past

相关标签:
13条回答
  • 2020-12-03 20:19

    Add an event handler for the textbox you want to be numeric only, and add the following code:

    private void textBoxNumbersOnly_KeyPress(object sender, KeyPressEventArgs e)
    {
       if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
       {
          e.Handled = false;
       }
       else
       {
          e.Handled = true;
       }
    }
    

    This allows for numbers 0 to 9, and also backspaces (useful IMHO). Allow through the '.' character if you want to support decimals

    0 讨论(0)
  • 2020-12-03 20:21

    There is a control in the framework which is specially made for numeric input : the NumericUpDown control. It also manages decimal values.

    0 讨论(0)
  • 2020-12-03 20:24

    here how to do this in vb.net

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Dim reg As New System.Text.RegularExpressions.Regex("[^0-9_ ]")
        TextBox1.Text = reg.Replace(TextBox1.Text, "")
    End Sub
    

    just fix the regex for your specific needs

    0 讨论(0)
  • 2020-12-03 20:24

    Being a novice you might be better off investing in a good third party toolkit. Radcontrols from Telerik for instance has a numeric textbox that will accomplish what you are looking for.

    0 讨论(0)
  • 2020-12-03 20:26
            if ("1234567890".IndexOf(e.KeyChar.ToString()) > 0)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
    
    0 讨论(0)
  • 2020-12-03 20:30

    i would probably use a regular expression to screen out non-numerics.

    pseudo code:

    for (each item in the input string) {
       if (!match(some regular expression, item)) {
            toss it out
       } else {
            add item to text box or whatever you were going to do with it
       }
    
    }
    
    0 讨论(0)
提交回复
热议问题