使用sql server在c#中进行Datagrid过滤

时间:2010-02-11 09:03:27

标签: c# sql-server winforms

如何在datagrid中过滤数据,例如,如果您在student数字中选择组合框,然后在文本字段中输入1001。 1001中的所有记录都将显示在datagrid中。我正在使用sql server

private void button2_Click(object sender, EventArgs e)
{
    if (cbofilter.SelectedIndex == 0)
    {
        string sql;
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = "Server= " + Environment.MachineName.ToString() + @"\; Initial Catalog=TEST;Integrated Security = true";

        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds1 = new DataSet();
        ds1 = DBConn.getStudentDetails("sp_RetrieveSTUDNO");
        sql = "Select * from Test where STUDNO like '" + txtvalue.Text + "'";
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.CommandType = CommandType.Text;
        da.SelectCommand = cmd;
        da.Fill(ds1);

        dbgStudentDetails.DataSource = ds1;
        dbgStudentDetails.DataMember = ds1.Tables[0].TableName;
        dbgStudentDetails.Refresh();
    }
    else if (cbofilter.SelectedIndex == 1)
    {
        //string sql;
        //SqlConnection conn = new SqlConnection();
        //conn.ConnectionString = "Server= " + Environment.MachineName.ToString() + @"\; Initial Catalog=TEST;Integrated Security = true";

        //SqlDataAdapter da = new SqlDataAdapter();
        //DataSet ds1 = new DataSet();
        //ds1 = DBConn.getStudentDetails("sp_RetrieveSTUDNO");
        //sql = "Select * from Test where Name like '" + txtvalue.Text + "'";
        //SqlCommand cmd = new SqlCommand(sql,conn);
        //cmd.CommandType = CommandType.Text;
        //da.SelectCommand = cmd;
        //da.Fill(ds1);

        // dbgStudentDetails.DataSource = ds1;
        //dbgStudentDetails.DataMember = ds1.Tables[0].TableName;
        //ds.Tables[0].DefaultView.RowFilter = "Studno = + txtvalue.text + "; 
        dbgStudentDetails.DataSource = ds.Tables[0];
        dbgStudentDetails.Refresh();
    }
}

2 个答案:

答案 0 :(得分:0)

很难回答一个模糊的问题。我想你必须使用包含用户输入的WHERE语句来调整SQL查询。

如果在组合框中选择了“学号”,请像这样查询(以数字开头):

SELECT id, name, number FROM students WHERE number LIKE @search + '%'

如果选择“学生姓名”,请使用其他查询(包含姓名):

SELECT id, name, number FROM students WHERE name LIKE '%' + @search + '%'

请解释C#的含义。

答案 1 :(得分:0)

您没有说出您注释掉的代码有什么问题。你也没有说出Studno专栏的类型。

你有没有试过像:

ds1.Tables[0].DefaultView.RowFilter = "Studno = '" + txtvalue.text + "'";