如何使之只能将数字1或2输入到文本框中?您还可以使用Backspace键。文本框字符的最大长度为1。 我知道如何只输入数字:
$("#id <tag>:contains('Text want to replaced')").html("Text Want to replaced with");
$(".className <tag>:contains('Text want to replaced')").html("Text Want to replaced with");
答案 0 :(得分:1)
我将使用NumericUpDown控件代替TextBox。在那里,您可以将min设置为1,将max设置为2,并且用户可以输入数字或使用箭头键增加/减少。
如果必须使用TextBox,则将其MaxLength属性设置为1,并添加KeyDown事件和处理程序。在处理程序中,您可以执行以下操作:
if(!(e.KeyCode == Keys.D1 || e.KeyCode == Keys.D2 || E.KeyCode == Keys.Delete))
{
// Of course, you can add even more keys up there. For example, you might add Keys.Numpad1 etc...
e.handled = true;
}
因此,对于TextBox,您基本上已经做了正确的事情。
答案 1 :(得分:1)
使用SuppressKeyPress属性
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
/*
* 8: backspace
* 49: 1
* 50: 2
*/
int[] validKeys = {8, 49, 50};
if (!validKeys.Contains(e.KeyValue))
e.SuppressKeyPress = true;
}
答案 2 :(得分:0)
我想您所需要的只是文本框的TextChanged事件中的以下内容?
if (textbox.text != "1" && textbox.text != "2")
{
textbox.text = string.empty;
}
我不确定number != 8
是什么意思?
答案 3 :(得分:0)
char number = e.KeyChar;
if (number != '1' && number != '2' && number != '\b')
{
e.Handled = true;
}
或者只是
e.Handled = e.KeyChar != '1' && e.KeyChar != '2' && e.KeyChar != '\b';
或者为了更具表现力
private static readonly char[] allowedChars = { '1', '2', '\b' };
// ...
e.Handled = !allowedChars.Contains(e.KeyChar);
答案 4 :(得分:0)
您所需要的只是使用RegularExpressions,您可以使用表达式检查任何输入。
我认为您应该访问以下问题: Only allow specific characters in textbox