C# 只允许在C中键入数字而不允许在C中键入数字的文本框#
对于我的程序,输入员工信息-如ID、姓名、姓氏和年薪。我将ID和薪资框设置为数字向上向下,但我想将薪资框设置为只接受数字的文本框C# 只允许在C中键入数字而不允许在C中键入数字的文本框#,c#,string,decimal,C#,String,Decimal,对于我的程序,输入员工信息-如ID、姓名、姓氏和年薪。我将ID和薪资框设置为数字向上向下,但我想将薪资框设置为只接受数字的文本框 但是,当我尝试从numericupdown更改为文本框时,会出现一个错误,显示“无法隐式地将”字符串“转换为”十进制“。我还有另一个按钮,可以找到最低工资等,但问题是什么?我想创建一个例外,使文本框只接受数字,但它不允许我://如何在C#中创建数字文本框 以最简单的形式: protected override void OnKeyPress(KeyPressEven
但是,当我尝试从numericupdown更改为文本框时,会出现一个错误,显示“无法隐式地将”字符串“转换为”十进制“。我还有另一个按钮,可以找到最低工资等,但问题是什么?我想创建一个例外,使文本框只接受数字,但它不允许我://如何在C#中创建数字文本框
以最简单的形式:
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
这段代码只接受任何不是数字的击键。MSDN链接解释了如何处理小数点等问题
但是,当我尝试从numericupdown更改为文本框时,会出现一个错误,显示“无法隐式地将”字符串“转换为”十进制“
在我看来,这像是一个铸造错误
employee.EmployeeId = (int)idNumericUpDown.Value;
请尝试以下方法:
employee.EmployeeId = decimal.Parse(idNumericUpDown.Value);
还可以查看更干净的
TryParse
。这是我一直为我的文本框所做的
函数(允许所有数值和退格键):
这是我发现的一个黑客。你可以通过以下方式隐藏NumericUpDown控件的箭头:
private void RemoveArrows(NumericUpDown numericUpDown)
{
Control updown = numericUpDown.Controls[0];
updown.Left += updown.Width;
updown.Visible = false;
}
只需为NumericUpDown控件调用此方法(例如,在Form_Load事件处理程序上):
其他方法-或使用解析和验证:
CausesValidation
属性设置为true
(默认为true)^\d*$
(任意长度的整数),也可以复杂到^(\d{1,3}(,?\d\d\d)*(.\d{1,})?$
(带有可选逗号和可选小数部分的数字)。将其分配给从文本框派生的新控件的公共属性
然后,在派生文本框中覆盖OnKeyPress,使其看起来像这样:
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!Regex.Match(new StringBuilder(Text).Append(e.KeyChar).ToString(), MaskPattern))
{
e.Handled = true;
}
else
base.OnKeyPress(e);
}
与Robert Harvey的答案非常相似,此方法将“吞下”任何添加到文本框当前文本值后与正则表达式不匹配的按键。您不仅可以将此MaskedTextBox用于数字输入,还可以用于只需要字母值、字母数字值(无符号或空白)的文本框,有效的本地或网络路径、IP地址等。WPF?WinForms?WebForms?其他一些表单?当我这样做时,它不喜欢“值”“分手?总是这样,你还能在这样的文本框上使用复制/粘贴吗?@comecme:这是个好问题
OnKeyPress
,顾名思义,它只验证击键。@RobertHarvey:是的,但我的意思是使用Shift+Ins或Ctrl+V进行粘贴,我认为这是击键。
private void RemoveArrows(NumericUpDown numericUpDown)
{
Control updown = numericUpDown.Controls[0];
updown.Left += updown.Width;
updown.Visible = false;
}
private void Form2_Load(object sender, EventArgs e)
{
RemoveArrows(idNumericUpDown);
RemoveArrows(salaryNumericUpDown);
}
private void NumericTextBox_Validating(object sender, CancelEventArgs e)
{
TextBox textBox = sender as TextBox;
decimal value;
if (Decimal.TryParse(textBox.Text, out value))
{
errorProvider1.SetError(textBox, "");
return;
}
e.Cancel = true;
errorProvider1.SetError(textBox, "Only numeric values allowed");
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!Regex.Match(new StringBuilder(Text).Append(e.KeyChar).ToString(), MaskPattern))
{
e.Handled = true;
}
else
base.OnKeyPress(e);
}