我有3个DataGridViews . 使用DataGridView1和DataGridView2,您可以选择行 . 按下按钮后,将比较DataGridView1和DataGridView2中的行,并在DataGridView3中设置具有相同值的每一行 .
我想要的是当您在DataGridView3中选择一行时,在DataGridView1和DataGridView2中选择相同的行 .
我的代码,也有效:
private int ShowSelected(int selectedId, Boolean sBool)
{
DataTable dt = DataGridView1.DataSource;
if(!sBool)
currentGrid = DataGridView1;
int indexCounter = 0;
foreach (DataRow dr in dt.Rows)
{
int cellIdDgv = Convert.ToInt32(dr["cellId"]);
if (selectedId == cellIdDgv)
{
if (sBool)
{
DataGridView1.Rows[indexCounter].Selected = true;
DataGridView1.FirstDisplayedCell = DataGridView1.Rows[indexCounter].Cells[0];
}
else
{
DataGridView2.Rows[indexCounter].Selected = true;
DataGridView2.FirstDisplayedCell = DataGridView2.Rows[indexCounter].Cells[0];
}
}
indexCounter++;
}
}
但我想要的是这样的东西,所以你不必遍历整个网格:
string selection = "cellId = " + selectedId;
DataRow[] drResult = dt.Select(selection);
int rowId = drResult.RowId;
if (sBool)
{
DataGridView1.Rows[rowId].Selected = true;
DataGridView1.FirstDisplayedCell = DataGridView1.Rows[rowId].Cells[0];
}
else
{
DataGridView2.Rows[rowId].Selected = true;
DataGridView2.FirstDisplayedCell = DataGridView2.Rows[rowId].Cells[0];
}
我怎样才能做到这一点?
1 回答
扩展我的评论并提供本地(stackoverflow)解决方案:
使用BindingSource.Filter属性完成过滤 . MSDN上提供的示例是:
为了简化操作,您可能需要创建一个
FilterBuilder
.编辑:为了避免过滤或问题中提到的上述循环,使用
BindingSource
等创建DataTable
,然后链接到您的`DataGridView1:要查找数据中的相关行,可以使用它来输入
DataGridView
中的Selection()
.我希望这有帮助 .