C# DataGridView中的搜索按钮。窗口窗体

C# DataGridView中的搜索按钮。窗口窗体,c#,.net,datagridview,C#,.net,Datagridview,我有一个带有DataGridView的Windows窗体,它绑定到SQLServer。我想用一个按钮设置具有特定Id的行的焦点。该Id在文本框中给出 过滤的想法并不能解决我的问题,因为我需要的是行号,而不是Id。 DataGridView有二十万行。我不确定是否要检查循环中的每一行 如何获取具有特定值的DataGridViewRow的IndexRow?一种方法是在表单中设置私有BindingSource,然后将从SQL Server加载的DataTable设置为BindingSource的数据源

我有一个带有DataGridView的Windows窗体,它绑定到SQLServer。我想用一个按钮设置具有特定Id的行的焦点。该Id在文本框中给出

过滤的想法并不能解决我的问题,因为我需要的是行号,而不是Id。
DataGridView有二十万行。我不确定是否要检查循环中的每一行


如何获取具有特定值的DataGridViewRow的IndexRow?

一种方法是在表单中设置私有BindingSource,然后将从SQL Server加载的DataTable设置为BindingSource的数据源,然后使用BindingSource作为DataGridView的数据源

使用一个文本框(位于其命名的IdentifierTextBox下方),在表单上放置一个按钮,并使用BindingSource查找方法获取位置,如果结果为-1,则未找到id,否则Find方法的返回值将是DataGridView中的行索引,因此我们可以通过BindingSource的Position属性设置行

private void FindByIdentifierButton_Click(object sender, EventArgs e)
{
    if (int.TryParse(IdentifierTextBox.Text, out var identifierToFind))
    {
        var indexRow = _customerBindingSource.Find("Id", identifierToFind);
        if (indexRow > -1)
        {
            _customerBindingSource.Position = indexRow;
        }
        else
        {
            // failed to find id
        }
    }
    else
    {
        // value in TextBox is not a valid int
    }

}

注意,对于这么多的记录,很可能仍然需要时间,但是与DataGridView中的行相对应的时间会更少。使用BindingSource总是比查询实际的DataGridView更好。

一种方法是在表单中设置私有BindingSource,然后将从SQL Server加载的DataTable设置为BindingSource的数据源,然后使用BindingSource作为DataGridView的数据源

使用一个文本框(位于其命名的IdentifierTextBox下方),在表单上放置一个按钮,并使用BindingSource查找方法获取位置,如果结果为-1,则未找到id,否则Find方法的返回值将是DataGridView中的行索引,因此我们可以通过BindingSource的Position属性设置行

private void FindByIdentifierButton_Click(object sender, EventArgs e)
{
    if (int.TryParse(IdentifierTextBox.Text, out var identifierToFind))
    {
        var indexRow = _customerBindingSource.Find("Id", identifierToFind);
        if (indexRow > -1)
        {
            _customerBindingSource.Position = indexRow;
        }
        else
        {
            // failed to find id
        }
    }
    else
    {
        // value in TextBox is not a valid int
    }

}
注意,对于这么多的记录,很可能仍然需要时间,但是与DataGridView中的行相对应的时间会更少。最好针对BindingSource而不是针对实际的DataGridView进行查询