Allow only integers in TextBoxes

后端 未结 6 1363
情书的邮戳
情书的邮戳 2021-01-22 12:45

I\'m having a problem with checking textboxes and making sure there\'s only integers in them.

So far I\'m able to confirm that there\'s text in the textboxes, but checki

相关标签:
6条回答
  • 2021-01-22 13:16

    You can use the int.TryParse method to check if the string is an integer:

    int n = 0;
    bool isNumber = int.TryParse(textBox1.Text, out n);
    
    if (!isNumber)
       return;
    
    0 讨论(0)
  • 2021-01-22 13:16

    If you ever start using ajax tool kit, keep this for your records

    <ajaxToolkit:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" TargetControlID="FUND_CD" FilterType="Custom" ValidChars="1234567890" runat="server">
                            </ajaxToolkit:FilteredTextBoxExtender>
    
    0 讨论(0)
  • 2021-01-22 13:26

    Using your current pattern, something like this:

    int tester;
    if (!Int32.TryParse(textBox1.Text, out tester))
    {
        errorProvider1.SetError(textBox1, "must be integer");
        return;
    }
    
    0 讨论(0)
  • 2021-01-22 13:31

    Why don't you use a MaskedTextBox?

    0 讨论(0)
  • 2021-01-22 13:36

    Override the Validating event in your form's textboxes and then you can do a TryParse on the contents.

    public void textBox1_Validating(...)
    {
      // TryParse
    }
    
    0 讨论(0)
  • 2021-01-22 13:38

    If you don't want to permit ANYTHING except numbers into the editbox, hook into keyboard events, check for characters that aren't digits and cancel them out.

    When you sort out what events are needed on one textbox, just reuse same event on others, since you don't have to copy events around.

    0 讨论(0)
提交回复
热议问题