numeric-only textbox as a control in Visual Studio

2020-01-31 12:00发布

问题:

I would like to make one numeric-only textbox. I'd like to then add that same to the control toolbox within Visual Studio 2008

I've already built the function to allow only numeric.

How can I make it available in the toolbox?

回答1:

This is how you can create numeric TextBox:

public class NumericTextBox : TextBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }
        base.OnKeyPress(e);
    }
}


回答2:

Call this method on key press

  function NumberOnly(evt)
  {
     var charCode = (evt.which) ? evt.which : event.keyCode
     if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

     return true;
  }


回答3:

Hi you can do something like this in the textchanged event of the textbox.

here is a demo

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        string actualdata = string.Empty;
        char[] entereddata = textBox1.Text.ToCharArray();
        foreach (char aChar in entereddata.AsEnumerable())
        {
            if (Char.IsDigit(aChar))
            {
                actualdata = actualdata + aChar;
                // MessageBox.Show(aChar.ToString());
            }
            else
            {
                MessageBox.Show(aChar + " is not numeric");
                actualdata.Replace(aChar, ' ');
                actualdata.Trim();
            }
        }
        textBox1.Text = actualdata;
    }


回答4:

Don't reinvent the wheel. Download this:
http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/NumericUpDown/NumericUpDown.aspx

EDIT:

Okay. I am getting downvoted for some three-year old advice. Currently, I would recommend looking into the contents of jQuery UI.