禁用文本框内的负值

问题描述 投票:0回答:3

我正在Windows窗体上工作。我需要我的文本框不接受负值..我该如何做..是否有可用的属性来做相同的事情...

c# winforms textbox
3个回答
3
投票
您需要编写文本框的按键事件,如:

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; } } }


1
投票
是的,您可以在文本框的textchanged事件中编写以下代码部分

0
投票
仅使用最小值和模式将不允许输入负值
© www.soinside.com 2019 - 2024. All rights reserved.