即使有!=,也会显示搜索项目

时间:2013-09-08 22:35:03

标签: c# asp.net

我的网站在虚拟数据库中搜索押韵。在代码中,如果文本框是!=执行搜索,否则显示错误,但是,即使搜索框中没有任何内容,它也会显示结果。那是为什么?

protected void Page_Load(object sender, EventArgs e)
    {
        ListBox1.Items.Clear();
        if (Page.PreviousPage != null)
        {
            TextBox SourceTextBox =
              (TextBox)Page.PreviousPage.FindControl("TextBox1");
            if (SourceTextBox != null)
            {
                cnn.Open();
                SqlCommand cmd = new SqlCommand("SELECT kelimeler FROM kelimelerim WHERE kelimeler LIKE @searchkey", cnn);
                cmd.Parameters.AddWithValue("@searchkey", "%" + SourceTextBox.Text);
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        ListBox1.Items.Add(dr.GetString(0));
                    }
                }
                cnn.Close();
            }

            else
            {
                ListBox1.Items.Add("Lütfen bir harf giriniz");
            }
        } 
    }

3 个答案:

答案 0 :(得分:1)

变量SourceTextBox永远不会为null,因为在帖子期间始终呈现并提交控件。您需要检查TextBox的文本而不是TextBox对象,以确定是否已输入任何文本。

if (!string.IsNullOrEmpty(SourceTextBox.Text))
{
    /* do stuff */
}

答案 1 :(得分:1)

您正在检查控件是否存在。 当然它存在,你已经创造了它。

您必须检查它的值是否为空

答案 2 :(得分:0)

if (SourceTextBox != null)
{

}

更改此格式

if (SourceTextBox.Text != null || !String.isNullorEmpty(SourceTextbox.Text))
{

}