Find a row in dataGridView based on column and value

前端 未结 7 1404
轻奢々
轻奢々 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:17

    This builds on the above answer from Gordon--not all of it is my original work. What I did was add a more generic method to my static utility class.

    public static int MatchingRowIndex(DataGridView dgv, string columnName, string searchValue)
            {
            int rowIndex = -1;
            bool tempAllowUserToAddRows = dgv.AllowUserToAddRows;
    
            dgv.AllowUserToAddRows = false; // Turn off or .Value below will throw null exception
            if (dgv.Rows.Count > 0 && dgv.Columns.Count > 0 && dgv.Columns[columnName] != null)
                {
                DataGridViewRow row = dgv.Rows
                    .Cast()
                    .FirstOrDefault(r => r.Cells[columnName].Value.ToString().Equals(searchValue));
    
                rowIndex = row.Index;
                }
            dgv.AllowUserToAddRows = tempAllowUserToAddRows;
            return rowIndex;
            }
    

    Then in whatever form I want to use it, I call the method passing the DataGridView, column name and search value. For simplicity I am converting everything to strings for the search, though it would be easy enough to add overloads for specifying the data types.

    private void UndeleteSectionInGrid(string sectionLetter)
            {
            int sectionRowIndex = UtilityMethods.MatchingRowIndex(dgvSections, "SectionLetter", sectionLetter);
            dgvSections.Rows[sectionRowIndex].Cells["DeleteSection"].Value = false;
            }
    

提交回复
热议问题