2010-05-29 60 views
1

我想爲我的程序添加搜索功能。有具有這種功能的類:將搜索結果綁定到數據網格

public DataTable Search() 
     { 
      string SQL = "Select * from Customer where " + mField + " like '%" + mValue + "%'"; 
      DataTable dt = new DataTable(); 
      dt = dm.GetData(SQL); 
      return (dt); 

     } 

有用於mFieldmValue setter和getter屬性。 DMDataManagement類的對象,其具有方法GetData

public DataTable GetData(string SQL) 
    { 
     SqlCommand command = new SqlCommand(); 
     SqlDataAdapter dbAdapter = new SqlDataAdapter(); 
     DataTable DataTable = new DataTable(); 

     command.Connection = clsConnection.GetConnection(); 
     command.CommandText = SQL; 
     dbAdapter.SelectCommand = command; 
     dbAdapter.Fill(DataTable); 
     return (DataTable); 
    } 

的搜索功能目前是這樣實現的:

private void btnfind_Click(object sender, EventArgs e) 
    { 
     //cust is the object of class customer// 
     if (tbCustName.Text != "") 
     { 
      cust.Field="CustName"; 
      cust.Value = tbCustName.Text; 
     } 
     else if (tbAddress.Text != "") 
     { 
      cust.Value = tbAddress.Text; 
      cust.Field="Address"; 
     } 
     else if (tbEmail.Text != "") 
     { 
      cust.Value = tbEmail.Text; 
      cust.Field="Email"; 
     } 
     else if (tbCell.Text != "") 
     { 
      cust.Value = tbCell.Text; 
      cust.Field = "Cell"; 
     } 

     DataTable dt = new DataTable(); 
     dt = cust.Search(); 
     dgCustomer.DataSource = dt; 
     RefreshGrid(); 
    } 

    private void RefreshGrid() 
    { 
     DataTable dt = new DataTable(); 
     dt = cust.GetCustomers(); 
     dgCustomer.DataSource = dt; 
    } 

這是行不通的。我不知道爲什麼。請幫忙。

回答

1

在您的RefreshGrid()方法中添加一個DataBind()聲明,以使您的新結果實際顯示在網格上。

private void RefreshGrid() 
{ 
    DataTable dt = cust.GetCustomers(); 
    dgCustomer.DataSource = dt; 
    dgCustomer.DataBind(); 
} 

考慮修改其他方法還有:

  1. 你的ad-hoc SQL有SQL注入漏洞。停止一切,直到你解決它!
  2. btnfind_Click不需要最終調用cust.Search()兩次。

    private void btnfind_Click(object sender, EventArgs e) 
    { 
        //<snip> 
        // no need to do all this twice. 
        // DataTable dt = new DataTable(); 
        // dt = cust.Search(); 
        // dgCustomer.DataSource = dt; 
        RefreshGrid(); 
    
    } 
    
+0

但是已經有一個重新格網? :s – Abid 2010-05-29 14:11:00

+0

我的意思是我編輯以前的refereshgrid函數還是做一個新的函數? – Abid 2010-05-29 14:11:45

0

RefreshGrid方法覆蓋DataSourcebtnfind_Click設置...不調用它,只需調用DataBind

private void btnfind_Click(object sender, EventArgs e) 
{ 
    ... 

    DataTable dt = cust.Search(); 
    dgCustomer.DataSource = dt; 
    dgCustomer.DataBind(); 

} 

順便說一句,你不需要如果您立即將其設置爲cust.Search的結果,則將新的DataTable分配給dt ...您只是創建了一個空白的實例(我將它固定在上面的代碼中)

相關問題