2017-04-08 126 views
0

具有DataGrind在Windows應用程序中啓用搜索選項,如Microsoft Excel搜索整個工作表(DataGrid)。通過DataGridView搜索行和列循環

foreach (DataGridViewRow row in DisplayGridView.Rows) 
     { 
      foreach (DataGridViewCell cell in row.Cells) 
      { 
       if (cell.Value == searchValue) 
       { 
        cell.Selected = true; 
        break; 
       } 
      } 
     } 

我已經試過上面的方法,但沒有得到結果。我有這個代碼impliment

​​

仍然,結果是null任何人都可以提示代碼。

回答

0

我假設你沒有檢查空值。添加這些空值檢查似乎按照您的描述工作。在Value之後,將ToString()方法添加到行中:cell.Value == searchValue使比較成功。此外休息是不需要的。

DisplayGridView.ClearSelection(); 
foreach (DataGridViewRow row in DisplayGridView.Rows) { 
    foreach (DataGridViewCell cell in row.Cells) { 
    if (cell.Value != null) { 
     if (cell.Value.ToString() == searchValue) { 
     cell.Selected = true; 
     } 
    } 
    } 
} 

下一頁方法

DisplayGridView.ClearSelection(); 
foreach (DataGridViewRow row in DisplayGridView.Rows) { 
    for (int i = 0; i < DisplayGridView.Columns.Count; i++) { 
    if (row.Cells[i].Value != null) { 
     if (row.Cells[i].Value.ToString().Equals(searchValue)) { 
     row.Cells[i].Selected = true; 
     } 
    } 
    } 
} 

如果你想突出的小區如果搜索字符串包含在細胞中的字符串,那麼你只需要改變equals方法來包含。

DisplayGridView.ClearSelection(); 
    foreach (DataGridViewRow row in DisplayGridView.Rows) { 
    foreach (DataGridViewCell cell in row.Cells) { 
     if (cell.Value != null) { 
     if (cell.Value.ToString().Contains(searchValue)) { 
      cell.Selected = true; 
     } 
     } 
    } 
    } 

希望這會有所幫助。

+0

不,這是行不通的;(我想你的代碼 –

+0

我張貼的作品,當我跑它的代碼沒有得到任何錯誤的第一行第一列只是我的光標移動無結果寄存 – JohnG

+0

然後?你應該調試它,把一個消息框放在搜索值匹配的位置,並且單元格被設置爲選中狀態,如果你看到消息框並且沒有選中單元格,那麼在此之後會發生一些事情,如果你從未看到消息框,那麼找不到搜索字符串 –