2

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!

2 Answers 2

7

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;
}
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.