【问题标题】:datagridview only searching first rowdatagridview 只搜索第一行
【发布时间】:2014-04-06 22:30:01
【问题描述】:

我正在尝试在我的 datagridview 中的每个单元格中搜索值“test”。但是它只搜索第一行......(我相信它正在搜索所有列)关于如何解决这个问题的任何想法?

dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
            string searchValue = "test";

            int searching = -1;
            while (searching < 7)
            {
                searching++;
                try
                {
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        if (row.Cells[searching].Value.ToString().Equals(searchValue))
                        {

                            row.Cells[searching].Selected = true;
                            break;
                        }
                    }
                }
                catch (Exception exc)
                {
                   // MessageBox.Show(exc.Message);
                }
            }

【问题讨论】:

    标签: c# search datagridview cell


    【解决方案1】:

    使用这个 sn-p.. 基本上我们遍历每一行/列,并在找到匹配项时将其值设置为选中。

    dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
    string searchValue = "test";
    
    for (int row = 0; row < dataGridView1.Rows.Count; ++row)
    {
     for (int col = 0; col < dataGridView1.Columns.Count; ++col)
     {
      var cellValue = dataGridView1.Rows[row].Cells[col].Value;
    
      if (cellValue != null && cellValue.ToString().Equals(searchValue))
      {
       dataGridView1.Rows[row].Cells[col].Selected = true;
    
       // if you want to search every cell for the searchValue then you shouldn't break.
       // break;
      } 
     }
    }
    

    您也可以使用简洁的 LINQ 代码执行上述操作:

    dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
    string searchValue = "test";
    
    dataGridView1.Rows.ToList().ForEach(row => row.Cells.ToList().ForEach(cell => 
    {
     cell.Selected = (cell.Value != null && cell.Value.ToString().Equals(searchValue));
    }));
    

    【讨论】:

      猜你喜欢
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多