我正在Windows窗体上工作。我需要我的文本框不接受负值..我该如何做..是否有可用的属性来做相同的事情...
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
您还可以使用数字上下控件来防止取整值。UPDATE:
Ref:Sai Kalyan Akshinthala我的代码无法处理复制/粘贴的情况。用户可以通过复制/粘贴输入负值。因此,我认为Sai Kalyan Akshinthala的答案对这种情况是正确的,除了Length> = 2的微小变化。
private void textBox1_TextChanged(object sender, EventArgs e) { if(textBox1.Text.Length >= 2) { int acceptednumber = Convert.ToInt32(textBox1.Text); if(acceptednumber < 0) { textBox1.Text = ""; MessageBox.Show("-ve values are not allowed"); } else { textBox1.Text = textBox1.Text; } } }