CoderBeginner
CoderBeginner

Reputation: 53

How to use string.IsNullOrEmpty in Textbox?

I'm trying to display null value only if the textbox is empty. In my case even if i'm giving input in the textbox, it won't detect as null value. Kindly help me to solve my error please.

 protected void AnyTextBox_TextChanged(object sender, EventArgs e)
        {

            if ((string.IsNullOrEmpty(TextBox1.Text)))
            {
                TBResult1.Text = "N/A";
            }
            else
            {
                TBResult1.Text = TextBox1.ToString();
            }

 <asp:TextBox ID="TextBox1"  OnTextChanged="AnyTextBox_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
 <asp:TextBox ID="TBResult1"  OnTextChanged="AnyTextBox_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>

Upvotes: 1

Views: 10272

Answers (5)

Ali Umair
Ali Umair

Reputation: 1424

Check you conditions like this.i use this one and it works fine.

if(TextBox1.Text.Trim().Length > 0)
{
    //Perform your logic here
}

Otherwise you have to check these two functions

if (string.IsNullOrEmpty(TextBox1.Text.Trim()) || string.IsNullOrWhiteSpace(TextBox1.Text.Trim()))
{

}

Upvotes: 0

Kurubaran
Kurubaran

Reputation: 8902

It should be like this, You have missed TextBox1.Text in the else part

     protected void AnyTextBox_TextChanged(object sender, EventArgs e)
            {

                if ((string.IsNullOrEmpty(TextBox1.Text)))
                {
                    TBResult1.Text = "N/A";
                }
                else
                {
                    TBResult1.Text = TextBox1.Text.ToString();
                }
            }

Upvotes: 0

keyboardP
keyboardP

Reputation: 69372

Replace

TBResult1.Text = TextBox1.ToString();

with

TBResult1.Text = TextBox1.Text;

Upvotes: 1

Ionică Bizău
Ionică Bizău

Reputation: 113365

From documentation:

String.IsNullOrEmpty Method

Indicates whether the specified string is null or an Empty string.

Example:

string s1 = "abcd"; // is neither null nor empty.
string s2 = "";     // is null or empty
string s3 = null;   // is null or empty

string.IsNullOrWhiteSpace(s1); // returns false
string.IsNullOrWhiteSpace(s2); // returns true
string.IsNullOrWhiteSpace(s3); // returns true

Also, you can do this:

if (string.IsNullOrEmpty(s1)) {
    Message.Show("The string s1 is null or empty.");
}

In your code:

if ((string.IsNullOrEmpty(TextBox1.Text)))
{
    // The TextBox1 does NOT contain text
   TBResult1.Text = "N/A";
}
else
{
    // The TextBox1 DOES contain text
    // TBResult1.Text = TextBox1.ToString();
    // Use .Text instead of ToString();
    TBResult1.Text = TextBox1.Text;
}

Upvotes: 2

coder
coder

Reputation: 13248

Try this:

 if(string.IsNullOrWhiteSpace(this.textBox1.Text))
    {
      MessageBox.Show("TextBox is empty");
    }

Upvotes: 0

Related Questions