我将 Windows 窗体与 C#
结合使用。我有一个带有 button1
和 textbox1
的表单。
我想要的是:当我单击 button1
时,如果 textbox1
包含任何零或零(仅零的任意组合),则显示警告消息,例如:
0
00
0000
000
000000000
我尝试了下面的代码,但如果 textbox1
有多个零(比如 000),它将不起作用
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
MessageBox.Show("Enter Value larger than zero);
}
当 button1
被点击时,如果 textbox1
有零的任意组合,我如何得到警告消息?
最佳答案
您可以通过执行以下操作来修剪 0 字符:
var text1 = "00000000";
var text2 = "00009000";
Console.WriteLine("Text1: {0}", string.IsNullOrWhiteSpace(text1.Trim('0')));
Console.WriteLine("Text2: {0}", string.IsNullOrWhiteSpace(text2.Trim('0')));
哪个返回:
Text1: true
Text2: false //Because we have 9 in the middle of the text.
在你的代码中你会有这样的东西:
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text.Trim('0'))
MessageBox.Show("Enter Value larger than zero");
}
关于c# - 如何检查文本框是否仅包含零并显示警告消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33856316/