Search code examples
c#datagridview

Getting datagridview cell index in C#


How to get Cell index after comparing values, for example i have this

 for (int i = 0; i < dataGridView1.Rows.Count; i++)
 {
     if (dataGridView1.Rows[i].Cells[value].Value.ToString() == radTextBox1.Text)
     {
     //If the value matches how to get the row index of that
     }              
 }

Solution

  • If you are wanting to find the value in any cell then you need to use a nested loop.

            dataGridView1.ClearSelection();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                for (int c = 0; c < dataGridView1.Columns.Count; c++)
                {
                    if (dataGridView1.Rows[i].Cell[c].Value != null)
                    {
                         if (dataGridView1.Rows[i].Cells[c].Value.ToString() == radtextBox1.Text)
                         {
                             dataGridView1.Rows[i].Selected = true;
                         }
                    }
                }
            }
    

    This will move through each row while checking all the columns for a value and will hilight any row where a cell has that value. Note that this code is case sensitive so "City" <> "city" but that is easily fixed using .ToUpper or .ToLower as needed.

    One other thing to add, this code also is based off a DGV that has AllowUserToAddRows set to false. If you need the edit row, you either need to -1 from the count in the rows loops or check to ensure that the current row is false for .IsNewRow.