Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification on how to use FirstDisplayedScrollingRowIndex

Just posted before and need clarification on a property. (Note I know this question is similar to others and hence I tried looking elsewhere for the solution but couldn't find the exact one for this situation).

I'm rather new to programming and don't know how to make a DataGridView scroll to the row selected by a user. I tried using FirstDisplayedScrollingRowIndex but am getting the following error:

Error: Cannot implicitly convert type 'System.Windows.Forms.DataGridViewRow' to 'int'

Which occurs when I try to bring the selected row by the user to the top of the datagridview:

dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[i]

Here is the full code:

String searchVal = textBox1.Text;

for (int i = 0; i < dataGridView1.RowCount; i++)
{
    if (dataGridView1.Rows[i].Cells[0].Value != null && dataGridView1.Rows[i].Cells[0].Value.ToString().Contains(searchVal))
    {
        dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[i];
        dataGridView1.Update();
    }
}
like image 786
Newuser Avatar asked Dec 03 '13 16:12

Newuser


2 Answers

According to the documentation, FirstDisplayedScrollingRowIndex:

Gets or sets the index of the row that is the first row displayed on the DataGridView.

You already have the index stored in i ... try just using that:

dataGridView1.FirstDisplayedScrollingRowIndex = i;

To address your second question in the comments, here's how you can find the first exact match (if any):

var selectedRow = dataGridView1.Rows.Cast<DataGridViewRow>()
                   .FirstOrDefault(x => Convert.ToString(x.Cells[0].Value) == searchVal);

if (selectedRow != null)
{
    dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[i];
    dataGridView1.Update();
}
like image 111
Grant Winney Avatar answered Oct 20 '22 00:10

Grant Winney


Just use i instead of dataGridView1.Rows[i]

dataGridView1.FirstDisplayedScrollingRowIndex = i;
like image 33
gleng Avatar answered Oct 20 '22 00:10

gleng