从数据库中检索一些数据

时间:2017-02-07 04:38:28

标签: c# asp.net sql-server sql-server-2012

我想从数据库中检索一些数据,但我遇到了问题

private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["homeworkConnectionString2"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select Id, FileName, Date from tblFiles where CourseName LIKE '%' + TextBox3.Text + '%'"; ;
            cmd.Connection = con;
            con.Open();

            GridView1.DataBind();
            con.Close();
        }
    }
}

the database

textbox3具有该数据

textbox

所以我要感谢的问题是" LIKE" ?

我把它改为:

private void BindGrid()
{
    string likeCondition = string.Empty;
    string textBoxContent = TextBox3.Text;
    var splittedContents = textBoxContent.Split(',').ToList();
    int index = 0;

    foreach (var splittedContent in splittedContents)
    {
        likeCondition += "CourseName LIKE %" + splittedContent + "%";
        index++;

        if (index != splittedContent.Length)
            likeCondition += " OR ";
    }

    string constr = ConfigurationManager.ConnectionStrings["homeworkConnectionString2"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select Id, FileName, Date from tblFiles where " + likeCondition; ; 
            cmd.Connection = con;
            con.Open();
            GridView1.DataBind();
            con.Close();
        }
    }
}

但它仍然无效 - 我该怎么办?

3 个答案:

答案 0 :(得分:1)

cmd.CommandText = "select Id, FileName, Date from tblFiles where CourseName LIKE '%' + TextBox3.Text + '%'"

您的字符串使用文字文本框名称。

你想要像

这样的东西
cmd.CommandText = "select Id, FileName, Date from tblFiles where CourseName LIKE '%" + TextBox3.Text + "%'"

然而,你最好使用顺序化查询

答案 1 :(得分:0)

cmd.CommandText = "select Id,Name from tblName where Name LIKE '%" + TextBox1.Text + "%'"

答案 2 :(得分:0)

您需要将TextBox3内容与,分开,并建立完整的条件。

我会按照以下方式进行:

            string likeCondition = string.Empty;
            string textBoxContent = "Programming1,Database";// use TextBox3.Text here
            var splittedContents = textBoxContent.Split(',').ToList();
            int index = 0;
            foreach (var splittedContent in splittedContents)
            {

                likeCondition += "CourseName LIKE %" + splittedContent + "%";
                index++;
                if (index != splittedContent.Length)
                    likeCondition += " OR ";

            }

现在,您应该按照以下方式在查询中使用likeCondition以上:

cmd.CommandText = "select Id, FileName, Date from tblFiles where " + likeCondition; ;