1

用户将关键字输入到必须在使用连接字符串连接到 c# 的数据库中搜索的文本框中,我想在数据库中搜索并显示用户输入的关键字的所有可能出现。

单击按钮后,我收到"Object reference not set to an instance of an object"指向该行的错误消息"ResultsQuery = Request.QueryString[TextBox1.Text].Split(' ');"

    public string[] ResultsQuery;
    public int i;
    public string criteria;
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {


            string connString = @"Data Source=ITLAPTOP\SQLEXPRESS;Initial Catalog=trial;Integrated Security=True";
            SqlConnection connStudent = new SqlConnection(connString);
            connStudent.Open();


            ResultsQuery = Request.QueryString[TextBox1.Text].Split(' ');

            foreach (string textbox1 in ResultsQuery)
            {
                 if(!string.IsNullOrEmpty(criteria))
                    criteria +="  OR ";

                     criteria += "SearchName LIKE '%" + textbox1 + "%' ";
            }

            string SqlInsertStatement = @"select * from trial.dbo.Student where Student.SearchName where '" + criteria;
            SqlCommand cmdTxt = new SqlCommand(SqlInsertStatement, connStudent);
            SqlDataReader dtrACode = cmdTxt.ExecuteReader();
            dtrACode.Read();


                try
                {
                    if ((dtrACode["SearchName"].ToString().Trim().Length != 0))
                    {

                    }
                    ListBox1.Items.Add(dtrACode["SearchName"].ToString());
                }
                catch (Exception)
                {
                    ListBox1.Items.Add("NO RECORD FOUND!");


                }


                connStudent.Close();
                connStudent.Dispose();

    }
4

1 回答 1

0

在尝试检索它之前检查查询字符串值是否存在,如下所示:

if (Request.QueryString[TextBox1.Text] != null) {
    ResultsQuery = Request.QueryString[TextBox1.Text].Split(' ');    
}
于 2013-08-23T02:38:48.517 回答