[c#] Find a row in dataGridView based on column and value

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 using:

dataGridView1.Rows[????].Selected = true;

The row ID I however do not know and the bindingsource keeps changing, thus row 10 could be "John Smith" in one instance but not even exist in another (I have a filter that filters out the source based on what user enters, so typing in "joh" would yield all rows where first / last name have "joh" in them, thus my list can go from 50 names to 3 in a click).

I want to find a way how I can select a row based on SystemId and a corresponding number. I can get the system ID using the following method:

systemId = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["SystemId"].Value.ToString();

Now I just need to apply it to the row selector. Something like dataGridView1.Columns["SystemId"].IndexOf(systemId} but that does not work (nor does such method exist). Any help is greatly appreciated.

This question is related to c# winforms datagridview

The answer is


This will give you the gridview row index for the value:

String searchValue = "somestring";
int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
{
    if(row.Cells[1].Value.ToString().Equals(searchValue))
    {
        rowIndex = row.Index;
        break;
    }
}

Or a LINQ query

int rowIndex = -1;

        DataGridViewRow row = dgv.Rows
            .Cast<DataGridViewRow>()
            .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue))
            .First();

        rowIndex = row.Index;

then you can do:

dataGridView1.Rows[rowIndex].Selected = true;

Try this:

        string searchValue = textBox3.Text;
        int rowIndex = -1;

        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        try
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Cells["peseneli"].Value.ToString().Equals(searchValue))
                {
                    rowIndex = row.Index;
                    dataGridView1.CurrentCell = dataGridView1.Rows[rowIndex].Cells[0];
                    dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Selected = true;

                    break;
                }
            }
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }

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<DataGridViewRow>()
                .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;
        }

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;

Those who use WPF

for (int i = 0; i < dataGridName.Items.Count; i++)
{
      string cellValue= ((DataRowView)dataGridName.Items[i]).Row["columnName"].ToString();                
      if (cellValue.Equals("Search_string")) // check the search_string is present in the row of ColumnName
      {
         object item = dataGridName.Items[i];
         dataGridName.SelectedItem = item; // selecting the row of dataGridName
         dataGridName.ScrollIntoView(item);                    
         break;
      }
}

if you want to get the selected row items after this, the follwing code snippet is helpful

DataRowView drv = dataGridName.SelectedItem as DataRowView;
DataRow dr = drv.Row;
string item1= Convert.ToString(dr.ItemArray[0]);// get the first column value from selected row 
string item2= Convert.ToString(dr.ItemArray[1]);// get the second column value from selected row 

Or you can use like this. This may be faster.

int iFindNo = 14;
int j = dataGridView1.Rows.Count-1;
int iRowIndex = -1;
for (int i = 0; i < Convert.ToInt32(dataGridView1.Rows.Count/2) +1; i++)
{
    if (Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value) == iFindNo)
    {
        iRowIndex = i;
        break;
    }
    if (Convert.ToInt32(dataGridView1.Rows[j].Cells[0].Value) == iFindNo)
    {
        iRowIndex = j;
        break;
    }
    j--;
}
if (iRowIndex != -1)
    MessageBox.Show("Index is " + iRowIndex.ToString());
else
    MessageBox.Show("Index not found." );

If you just want to check if that item exists:

IEnumerable<DataGridViewRow> rows = grdPdfs.Rows
            .Cast<DataGridViewRow>()
            .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue));
if (rows.Count() == 0) 
{
    // Not Found
} 
else 
{
    // Found
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to datagridview

How to refresh or show immediately in datagridview after inserting? Delete a row in DataGridView Control in VB.NET Looping each row in datagridview How to get cell value from DataGridView in VB.Net? Changing datagridview cell color based on condition Index was out of range. Must be non-negative and less than the size of the collection parameter name:index how to bind datatable to datagridview in c# DataGridView AutoFit and Fill How to export dataGridView data Instantly to Excel on button click? Populate a datagridview with sql query results