![](/img/trans.png)
[英]How to make telerik autocomplete text box to accept only 1 entry in c# winforms
[英]Text box to accept only number in C#
我正在使用法语键盘。 在顶部键盘上有键,如&,é,“,”,(, - ,è,_,ç,à)使用它作为数字我必须按shift或打开大写锁定。
我可以在24中放入文本框的最大数量。
上限为:我可以输入数字。 关闭capLock:我不能使用shift来输入数字。
我也可以在文本框中输入&,é,“,',(, - ,è,_,ç,à等值。
public class NumericalTextBox : TextBox
{
private int MaxValue;
public NumericalTextBox()
{
}
public NumericalTextBox(int max_value)
{
MaxValue = max_value;
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
if (e.KeyCode != Keys.Back)
{
e.SuppressKeyPress = true;
}
}
}
if (Control.ModifierKeys == Keys.Shift)
{
e.SuppressKeyPress = true;
}
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (MaxValue >= 0 && !char.IsControl(e.KeyChar) && char.IsDigit(e.KeyChar))
{
try
{
string s = this.Text + e.KeyChar;
int x = int.Parse(s);
if (x >= MaxValue)
e.Handled = true;
}
catch
{
//e.Handled = true;
}
}
base.OnKeyPress(e);
}
}
}
如果可以,请改用NumericUpDown -Control。 它为您提供了所希望的行为(过滤非数字值)。
但是,如果必须使用文本框,则Shtako-verflow的注释指向答案。
最佳答案的代码:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
有一种简单的方法可以实现这一目标。 您可以使用正则表达式验证器。
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ValidationExpression="^[0-9]+$"
ErrorMessage="Only Numbers" ControlToValidate="TextBox2"></asp:RegularExpressionValidator>
这将帮助您只接受Textbox的整数值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.