Kayla
Kayla

Reputation: 165

How can I set the value of textbox to "0" if blank or empty?

I'm trying to have a textbox, which if blank or empty, will have the number zero inserted into it once a button is clicked. So far I've been trying this code, below, to no avail. The code below is for the button_click method. What am I missing?

if (!string.IsNullOrEmpty(textBox2.Text))
{
    textBox2.Text = "0";                
}

Upvotes: 2

Views: 17194

Answers (4)

Hamid Pourjam
Hamid Pourjam

Reputation: 20754

You should remove !

if (string.IsNullOrEmpty(textBox2.Text))
{
    textBox2.Text = "0";                
}

! will negate the logical expression. It means not of something

so !string.IsNullOrEmpty(textBox2.Text) is true when string is (not empty) and (not null).

Upvotes: 4

Tony Wu
Tony Wu

Reputation: 1107

Simply add a if-statment into a TextChanged event of textbox to do the checking...

No idea why you need a button click event...

Upvotes: -1

Neal
Neal

Reputation: 811

Remove the ! before string.IsNull...

! is the same as having != (not equals)

Upvotes: 1

adv12
adv12

Reputation: 8551

Remove the "!". You want to change the text when the string is null or empty.

Upvotes: 1

Related Questions