gpt4 book ai didi

C# 同步绑定(bind)源和底层数据源

转载 作者:行者123 更新时间:2023-11-30 17:53:50 26 4
gpt4 key购买 nike

目前在引用数据绑定(bind)数据表中的行数据时遇到问题。绑定(bind)配置如下:DataGridView => BindingSource => 数据表

datagridview 允许多行选择和排序。

我有一个按钮,它根据选定的 datagridview 行启动一些方法:

ItemsBindingSource.DataSource = dataSets.Tables["ItemList"];

foreach(DataGridViewRow SelectedItem in datagridview1.SelectedRows)
{
string SelectedItemName = SelectedItem.Cells[1].Value.ToString();
int rowPosition = ItemsBindingSource.Find("Name",SelectedItemName);
RunSomeMethod(dataSets.Tables["ItemList"].Rows[RowPosition]);
}

void RunSomeMethod(DataRow row)
{
// run some code and modify the values of particular cells within the
// row and save the changes
}

我的问题是,当我对 Datagridview 进行排序时,所选项目的 rowPosition 不再与 BindingSource 的基础数据源的行位置匹配。我需要一些关于让绑定(bind)源和它的底层数据源同步的建议,或者也许是一个更好的方法来完成这个任务。感谢任何建议。

*编辑

我意识到我可以根据主键值引用行,例如:

foreach(DataGridViewRow selectedItem in datagridview1.SelectedRows)
{
int selectedItemPrimaryKey = selectedItem.Cells[0].value;
RunSomeMethod(dataSets.Tables["ItemList"].Rows.Find(selectedItemPrimaryKey));
}

没有我希望的那么漂亮,但似乎在做这项工作。仍然对其他建议持开放态度。我对数据绑定(bind)很陌生。

最佳答案

您可以使用另一个名为“RowID”的列,它对所有行都有唯一编号。然后找到包含此列而不是行索引的行。如果您对此有帮助,请告诉我,并随时寻求进一步的帮助。

关于C# 同步绑定(bind)源和底层数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16766811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com