2014-10-10 38 views
1

在datagridview中加載表後,我從datagrid列標題生成組合框的項目。從組合框中選擇列,我有一個用戶給出的搜索值的文本框。我使用下面的代碼:使用c在datagridview中搜索#

 string searchForText = txtCrudSearch.Text; 
     dgvLoadTable.ClearSelection(); 
     dgvLoadTable.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 
     try 
     { 
      foreach (DataGridViewRow row in dgvLoadTable.Rows) 
      { 
       if (row.Cells[cboCrudSearchColumn.SelectedIndex].Value.ToString().Equals(searchForText)) 
       { 
        row.Selected = true; 
        //if I use break here the code doesn't give exception 
        //but highlights only one row. I want to return all rows that 
        // match with the search string 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 

現在的問題是:

  1. 我得到的所有匹配的行強調了與例外
  2. 「未設置爲對象的實例對象引用」
  3. 如何才能返回所有匹配的行只在數據網格中,而不是突出顯示它們?
  4. 搜索區分大小寫,如何讓它適用於所有類型?

任何幫助將不勝感激,謝謝。

+0

錯誤可能在行「row.Cells [cboCrudSearchColumn.SelectedIndex] .Value.ToString()」。調試並告訴我什麼值返回這條線。 – Nacho 2014-10-10 11:33:07

+0

如果您使用DataTable作爲數據源,那麼http://stackoverflow.com/a/10049875/891715 – Arie 2014-10-10 11:38:08

+0

它說nullReference異常是未處理的,我使用實體模型作爲我的數據源。 – feather 2014-10-10 11:40:46

回答

0

我想通了。如果任何人需要解決方案,代碼如下:

private void btnCrudSearch_Click(object sender, EventArgs e) 
    { 

     dgvLoadTable.CurrentCell = null; 
     dgvLoadTable.AllowUserToAddRows = false; 
     dgvLoadTable.ClearSelection(); 
     dgvLoadTable.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 
     dgvLoadTable.ReadOnly = true; 

     try 
     { 
      foreach (DataGridViewRow row in dgvLoadTable.Rows) 
      { 
       var cellValue = row.Cells[cboCrudSearchColumn.SelectedIndex].Value; 
       if (cellValue != null && cellValue.ToString() == txtCrudSearch.Text.ToUpper()) 
       { 
        row.Selected = true; 
        row.Visible = true; 
       } 
       else 
        row.Visible = false; 

      } 
     } 
     catch (Exception exc) 
     { 
      MessageBox.Show(exc.Message); 
     } 

    }