2010-02-11 42 views
0

如何過濾datagrid中的數據,例如如果您在student數字中選擇了組合框,然後在文本字段中輸入1001。 1001中的所有記錄將顯示在datagrid中。我使用sql serverc#中使用sql server的Datagrid過濾器

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

回答

0

這是很難回答pricisely一個模糊的問題。我想你必須修改你的SQL查詢和包含用戶輸入的WHERE語句。

如果「學號」在組合框中選擇,這樣的查詢(從數字):

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

如果選擇「學生姓名」,使用另一個查詢(含名稱):

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

請解釋一下C#的含義。

+0

正如我在組合框中choosestudent數量和文本框爲1001學號輸入學號......它會顯示在DataGrid,但舊的數據仍然例如1002仍然在數據網格中 繼承人代碼 – 2010-02-11 11:59:50

+0

在調用da.Fill(ds)之前調用DataSet上的Clear()方法, – Mart 2010-02-11 21:48:40

0

你不會說你註釋掉的代碼有什麼問題。你也不會說什麼類型的Studno列。

你有沒有嘗試過這樣的:

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