naouf naouf - 3 months ago 17
C# Question

How to check if textbox contains only zero and display an alert message?

I use windows forms with

C#
. I have a form with
button1
and
textbox1
.

What I want is: When I click
button1
, display alert message if the
textbox1
contains any zero or zeros (any combination of zeros only) something like:

0
00
0000
000
000000000


I tried the following code but it will not work if
textbox1
has more than one zero (like 000)

private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
MessageBox.Show("Enter Value larger than zero);
}


How can I get alert message if
textbox1
has any combination of zeros when
button1
is clicked?

Answer

You can just trim the 0 char by doing something like this:

var text1 = "00000000";
var text2 = "00009000";

Console.WriteLine("Text1: {0}", string.IsNullOrWhiteSpace(text1.Trim('0')));
Console.WriteLine("Text2: {0}", string.IsNullOrWhiteSpace(text2.Trim('0')));

Which returns:

Text1: true

Text2: false //Because we have 9 in the middle of the text.

In your code you will have something like this:

private void button1_Click(object sender, EventArgs e)
{    
     if (string.IsNullOrWhiteSpace(textBox1.Text.Trim('0'))
           MessageBox.Show("Enter Value larger than zero");
}