C#在DataGridView中搜索列并选中该行

本文关键字:搜索 DataGridView | 更新日期: 2023-09-27 18:20:17

我需要一个函数,我可以提供一个DataGridView、列号和要搜索的字符串,它会根据要搜索的列和要查找的字符串选择DataGridView行。我有下面的基本函数,只是缺少了使其工作的一大块代码。想法?

public void dgvSearchSetCurrent(DataGridView oDataGrid, int iCol, string sSearch)
{
  if (oDataGrid.RowCount > 0)
  {
    bool iFound = false;
    //Search DG column and set select/set the current row
    //missing code here
    //if not found, set current row 0
    if (iFound == false)
    {
      oDataGrid.Rows[0].Selected = true;
    }
  }
}

C#在DataGridView中搜索列并选中该行

    public void dgvSearchSetCurrent(DataGridView oDataGrid, int iCol, string sSearch)
    {
        if (oDataGrid.RowCount > 0)
        {
            bool iFound = false;
            //Search DG column and set select/set the current row
            for(int i = 0 ; i < oDataGrid.Rows.Count ; i++)
            {
                if(oDataGrid.Rows[i].Cell[iCol].Value.ToString() == sSearch)
                //if(oDataGrid.Rows[i].Cell[iCol].Value.ToString().Contains(sSearch))
                {
                    iFount = true;
                    oDataGrid.Rows[i].Selected = true;
                    break; //If you want to select all rows contain sSearch, skip this line
                }
            }

            //if not found, set current row 0
            if (iFound == false)
            {
                oDataGrid.Rows[0].Selected = true;
            }
        }
    }