题
我需要一个文本,其中只有用户可以允许进入为整数。但用户不能进入零。i。e,他可以进入10,100人等等。不0单。我怎么可以做的事件表示?
解决方案
你打算做这样的方式,是对用户非常讨厌。你猜测用户想要进入,并在你的猜测起到什么,但你可以错了。
它也有孔,例如,用户可输入“10”,然后删除“1”。或者,他可以在一个“0”粘贴 - ?您允许粘贴,你不
所以我的解决办法是:让他进入他喜欢的任何数字,他喜欢的任何方式,并验证输入唯一的之后的说罢,例如,当输入失去焦点
其他提示
为什么不使用的NumericUpDown并进行以下设置:
upDown.Minimum = 1;
upDown.Maximum = Decimal.MaxValue;
使用 int。TryParse 将文本转换到一号检查,如果这个数字不是0。使用 验证 事件的检查。
// 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你应该看一看如何实现 验证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);
}
}
这是主题为另一变型:
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;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (textBox1.Text == "" && e.KeyChar == '0')
{
e.Handled = true;
return;
}
if (e.KeyChar < '0' || e.KeyChar > '9')
{
e.Handled = true;
return;
}
}
不是很好,但它的工作原理
不隶属于 StackOverflow