DataGridView- How to jump to the selected row in search?

18,532

Solution 1

I found out that I can use DataGridView.FirstDisplayedScrollingRowIndex Property to scroll to the selected row index and display it as the first row in DataGridView.

This is how I used in my program-

if (row.Cells[1].Value.ToString().Equals(materialLocation.MaterialID))
{
    rowIndex = row.Index;
    dgvSearchResults.ClearSelection();                            
    dgvSearchResults.Rows[rowIndex].Selected = true;
    dgvSearchResults.FirstDisplayedScrollingRowIndex = rowIndex;
    dgvSearchResults.Focus();
    break;
}

Solution 2

int rowIndex = -1;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Cells[0].Value.ToString().Equals(searchString))
    {
        rowIndex = row.Index;
        break;
    }
}
if (rowIndex >= 0)
{
    dataGridView1.CurrentCell = dataGridView1[visibleColumnIndex, rowIndex];
}

visibleColumnIndex - selected cell must be visible

Share:
18,532
Aung Kaung Hein
Author by

Aung Kaung Hein

Updated on June 13, 2022

Comments

  • Aung Kaung Hein
    Aung Kaung Hein almost 2 years

    I use the following code to find a row in DataGridView and highlight the row.

    private void btnSearch_Click(object sender, EventArgs e)
        {
            currentMode = ModeSelection.Search;
    
            if (cmbSearchBy.SelectedIndex == Convert.ToInt16(SearchBy.MaterialID))
            {
                dgvSearchResults.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                int rowIndex = -1;
                try
                {
                    foreach (DataGridViewRow row in dgvSearchResults.Rows)
                    {
                        if (row.Cells[1].Value.ToString().Equals(materialLocation.MaterialID))
                        {
                            //Select the row here
                            rowIndex = row.Index;
                            dgvSearchResults.Rows[rowIndex].Selected = true;
                            break;
                        }
                    }
                }
                catch (Exception ex) { throw ex; }
            }
    

    It works perfectly. Problem is my DataGridView has over 500 records and if the selected row is near the bottom of the DataGridView, users have to scroll all the way down to the bottom. Which code can I use to jump to the row that I am looking for? Any help will be very much appreciated!