Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I allow only 0 or 1 to be entered in a TextBox?

Tags:

c#

textbox

How can I limit the TextBox control to only allow the values 0 and 1?

Thanks. And I have one more question: How can I disable put text from clipboard in my textbox control?

like image 854
Alexry Avatar asked May 21 '10 13:05

Alexry


People also ask

How do I allow only numbers in a text box?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

Can you restrict the textbox to input numbers only?

You can use an <input type="number" /> . This will only allow numbers to be entered into othe input box.

How do I restrict characters in a textbox?

To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.

How do I restrict only numbers in a text box in HTML?

The <input type="number"> defines a field for entering a number. Use the following attributes to specify restrictions: max - specifies the maximum value allowed. min - specifies the minimum value allowed.


1 Answers

By using the event KeyPress

private void NumericOnlyKeyBox_KeyPress(object sender, KeyPressEventArgs e)
{
    var validKeys = new[] { Keys.Back, Keys.D0, Keys.D1 };

    e.Handled = !validKeys.Contains((Keys)e.KeyChar);
}

Setting e.Handled to true / false indicates if the character should be accepted to the box or not.

You can read more about KeyPressEventArgs on MSDN.

Note

Keys.Delete should cover Keys.Delete, Keys.Backspace and other "Back" buttons.

like image 76
Filip Ekberg Avatar answered Sep 22 '22 02:09

Filip Ekberg