根据列和值在dataGridView中查找一行 [英] Find a row in dataGridView based on column and value

查看:37
本文介绍了根据列和值在dataGridView中查找一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 3 列的 dataGridView:使用数据库信息绑定的 SystemId、FirstName、LastName.我想突出显示某一行,我会使用:

I have a dataGridView that has 3 columns: SystemId, FirstName, LastName that is bound using database information. I would like to highlight a certain row, which I would do using:

dataGridView1.Rows[????].Selected = true;

然而,我不知道行 ID 并且绑定源不断变化,因此第 10 行在一个实例中可能是John Smith",但在另一个实例中甚至不存在(我有一个过滤器,可以根据用户输入的内容过滤源,因此输入joh"将生成名字/姓氏中包含joh"的所有行,因此我的列表可以通过单击从 50 个名字变为 3 个).

The row ID I however do not know and the bindingsource keeps changing, thus row 10 could be "John Smith" in one instance but not even exist in another (I have a filter that filters out the source based on what user enters, so typing in "joh" would yield all rows where first / last name have "joh" in them, thus my list can go from 50 names to 3 in a click).

我想找到一种方法,如何根据 SystemId 和相应的数字选择一行.我可以使用以下方法获取系统 ID:

I want to find a way how I can select a row based on SystemId and a corresponding number. I can get the system ID using the following method:

systemId = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["SystemId"].Value.ToString();

现在我只需要将它应用到行选择器.类似于 dataGridView1.Columns["SystemId"].IndexOf(systemId} 但这不起作用(也不存在这种方法).非常感谢任何帮助.

Now I just need to apply it to the row selector. Something like dataGridView1.Columns["SystemId"].IndexOf(systemId} but that does not work (nor does such method exist). Any help is greatly appreciated.

推荐答案

这将为您提供值的 gridview 行索引:

This will give you the gridview row index for the value:

String searchValue = "somestring";
int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
{
    if(row.Cells[1].Value.ToString().Equals(searchValue))
    {
        rowIndex = row.Index;
        break;
    }
}

或 LINQ 查询

int rowIndex = -1;

DataGridViewRow row = dgv.Rows
    .Cast<DataGridViewRow>()
    .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue))
    .First();

rowIndex = row.Index;

那么你可以这样做:

dataGridView1.Rows[rowIndex].Selected = true;

这篇关于根据列和值在dataGridView中查找一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆