繁体   English   中英

如何在Textbox中使用string.IsNullOrEmpty?

[英]How to use string.IsNullOrEmpty in Textbox?

我只是在文本框为空时才尝试显示空值。 在我的情况下,即使我在文本框中输入,它也不会检测为空值。 请帮我解决我的错误。

 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>

来自文档:

String.IsNullOrEmpty方法

指示指定的字符串是null还是空字符串。

例:

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

此外,您可以这样做:

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

在你的代码中:

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

更换

TBResult1.Text = TextBox1.ToString();

TBResult1.Text = TextBox1.Text;

尝试这个:

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

它应该是这样的,你在else部分错过了TextBox1.Text

     protected void AnyTextBox_TextChanged(object sender, EventArgs e)
            {

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

检查你这样的条件。我使用这个,它工作正常。

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

否则你必须检查这两个功能

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM