Find a row in dataGridView based on column and value

前端 未结 7 1406
轻奢々
轻奢々 2020-12-07 14:54

I have a dataGridView that has 3 columns: SystemId, FirstName, LastName that is bound using database information. I would like to highlight a certain row, which I would do

相关标签:
7条回答
  • 2020-12-07 15:32

    The above answers only work if AllowUserToAddRows is set to false. If that property is set to true, then you will get a NullReferenceException when the loop or Linq query tries to negotiate the new row. I've modified the two accepted answers above to handle AllowUserToAddRows = true.

    Loop answer:

    String searchValue = "somestring";
    int rowIndex = -1;
    foreach(DataGridViewRow row in DataGridView1.Rows)
    {
        if (row.Cells["SystemId"].Value != null) // Need to check for null if new row is exposed
        {
            if(row.Cells["SystemId"].Value.ToString().Equals(searchValue))
            {
                rowIndex = row.Index;
                break;
            }
        }
    }
    

    LINQ answer:

    int rowIndex = -1;
    
    bool tempAllowUserToAddRows = dgv.AllowUserToAddRows;
    
    dgv.AllowUserToAddRows = false; // Turn off or .Value below will throw null exception
    
        DataGridViewRow row = dgv.Rows
            .Cast<DataGridViewRow>()
            .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue))
            .First();
    
        rowIndex = row.Index;
    
    dgv.AllowUserToAddRows = tempAllowUserToAddRows;
    
    0 讨论(0)
提交回复
热议问题