C# 文本框中不允许零
我需要一个文本框,只有用户可以允许输入整数。但是用户不能输入零。i、 他可以输入10100等,而不仅仅是0。 如何在按键下生成事件?用于将文本转换为数字,并检查该数字是否不是0。使用事件进行检查C# 文本框中不允许零,c#,wpf,forms,input-filtering,C#,Wpf,Forms,Input Filtering,我需要一个文本框,只有用户可以允许输入整数。但是用户不能输入零。i、 他可以输入10100等,而不仅仅是0。 如何在按键下生成事件?用于将文本转换为数字,并检查该数字是否不是0。使用事件进行检查 // this goes to you init routine textBox1.Validating += textBox1_Validating; // the validation method private void textBox1_Validating(object sender, C
// this goes to you init routine
textBox1.Validating += textBox1_Validating;
// the validation method
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text.Length > 0)
{
int result;
if (int.TryParse(textBox1.Text, out result))
{
// number is 0?
e.Cancel = result == 0;
}
else
{
// not a number at all
e.Cancel = true;
}
}
}
编辑:
好的,既然您使用了WPF,那么您应该看看如何实现。下面是一个实现上述逻辑的验证类:
public class StringNotZeroRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (textBox1.Text.Length == 0)
return new ValidationResult(true, null);
int result;
if (int.TryParse(textBox1.Text, out result))
{
// number is 0?
if (result == 0)
{
return new ValidationResult(false, "0 is not allowed");
}
}
else
{
// not a number at all
return new ValidationResult(false, "not a number");
}
return new ValidationResult(true, null);
}
}
为什么不使用NumericUpDown并进行以下设置:
upDown.Minimum = 1;
upDown.Maximum = Decimal.MaxValue;
private void textBox1\u按键(对象发送器,按键事件参数e)
{
如果(textBox1.Text==“”&e.KeyChar=='0')
{
e、 已处理=正确;
返回;
}
if(e.KeyChar<'0'| e.KeyChar>'9')
{
e、 已处理=正确;
返回;
}
}
不太好,但很管用这是主题的另一个变体:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
char newChar = Convert.ToChar(e.KeyValue);
if (char.IsControl(newChar))
{
return;
}
int value;
e.SuppressKeyPress = int.TryParse((sender as TextBox).Text + newChar.ToString(), out value) ? value == 0 : true;
}
您计划这样做的方式对用户来说非常烦人。您正在猜测用户想要输入什么,并根据您的猜测采取行动,但您可能大错特错 它也有漏洞,例如,用户可以输入“10”,然后删除“1”。或者他可以粘贴一个“0”——你允许粘贴,不是吗
因此,我的解决方案是:让他输入任何他喜欢的数字,任何他喜欢的方式,并且只在他完成后验证输入,例如,当输入失去焦点时。这将允许输入“10”,然后删除“1”。现在我正在这样做。但我会找到解决办法的。让我们试试。这正是我的解决方案使用验证事件并按建议忽略key*事件的原因。只有当用户完成输入时才进行验证。啊,错过了wpf标记,我的错。我不相信wpf有数字上下控件。我直到今天才使用wpf,我只是在他的问题中没有看到这个标记。在这种情况下,我会整理掉键关闭事件中的所有非数字输入,并在OnValidating中检查零(正如bart已经提到的),我认为您对问题的标记是令人困惑的,因为您有Winforms,但需要WPF答案。
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
char newChar = Convert.ToChar(e.KeyValue);
if (char.IsControl(newChar))
{
return;
}
int value;
e.SuppressKeyPress = int.TryParse((sender as TextBox).Text + newChar.ToString(), out value) ? value == 0 : true;
}