1

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>
1
  • 4
    It should be TBResult1.Text = TextBox1.Text; Commented May 26, 2013 at 18:09

5 Answers 5

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Replace

TBResult1.Text = TextBox1.ToString();

with

TBResult1.Text = TextBox1.Text;

Comments

0

Try this:

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

1 Comment

Thanks for helping, It work but it shows "System.Web.UI.WebControls.TextBox" after it detect there is string on the textbox
0

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

Comments

0

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()))
{

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.