关于如何使用 FirstDisplayedScrollingRowIndex 的说明

New*_*ser 5 c# datagridview winforms

之前刚刚发布,需要澄清一个属性。(注意我知道这个问题与其他问题类似,因此我尝试在别处寻找解决方案,但找不到适合这种情况的确切解决方案)。

我对编程很陌生,不知道如何DataGridView滚动到用户选择的行。我尝试使用FirstDisplayedScrollingRowIndex但出现以下错误:

错误:无法将类型“System.Windows.Forms.DataGridViewRow”隐式转换为“int”

当我尝试将用户选择的行带到 datagridview 的顶部时会发生这种情况:

dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[i]
Run Code Online (Sandbox Code Playgroud)

这是完整的代码:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Gra*_*ICA 4

根据文档,FirstDisplayedScrollingRowIndex

获取或设置 DataGridView 上显示的第一行的行索引。

您已经将索引存储在i...尝试使用它:

dataGridView1.FirstDisplayedScrollingRowIndex = i;
Run Code Online (Sandbox Code Playgroud)

为了解决评论中的第二个问题,您可以通过以下方法找到第一个完全匹配的内容(如果有):

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();
}
Run Code Online (Sandbox Code Playgroud)