Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 868
Aung Kaung Hein Avatar asked Nov 24 '25 03:11

Aung Kaung Hein


1 Answers

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;
}
like image 124
Aung Kaung Hein Avatar answered Nov 26 '25 17:11

Aung Kaung Hein