我有一个 dataGridView,当我点击任何一行时,会打开一个表单来更新行数据,但更新完成后,更新表单关闭了,但是 dataGridView 中的数据没有更新。
如何解决这个问题?
如何解决这个问题?
BindingSource
是一种不使用第三方ORM的方式,虽然一开始可能会感觉有些冗长,但在BindingSource
上拥有一个更新方法所带来的好处是非常有帮助的。
如果你的数据源是例如用户字符串列表的话
List<string> users = GetUsers();
BindingSource source = new BindingSource();
source.DataSource = users;
dataGridView1.DataSource = source;
完成编辑后,只需更新数据对象,无论是DataTable
还是像这样的用户字符串列表,并在BindingSource
上进行ResetBindings
操作。
users = GetUsers(); //Update your data object
source.ResetBindings(false);
IBindingList
,但不幸的是,它也不能与 BindingList<T>
一起使用。 - TobyDataGridView dg1 = new DataGridView();
dg1.DataSource = src1;
// Update Data in src1
dg1.DataSource = null;
dg1.DataSource = src1;
我知道这是一个老话题,但我突然找到了最好的方法,并且不需要使数据源失效并重新分配它。只需使用BindingList而不是List即可。
例如:
//declare your list
private BindingList<myclass> mMyList = new BindingList<myclass>();
//then bind it to your datagrid, i usually do it on the Load event
private void Form1_Load(object sender, EventArgs e)
{
_dgMyDatagrig.DataSource = mMyList;
}
//start populating your list
private void addItem(mycclass item)
{
mMylist.add(item);
//the datagrid will show automatically the new added/updated items, no need to do anything else
}
我知道我来晚了,但希望这能帮助那些使用类绑定的人
var newEntry = new MyClassObject();
var bindingSource = dataGridView.DataSource as BindingSource;
var myClassObjects = bindingSource.DataSource as List<MyClassObject>;
myClassObjects.Add(newEntry);
bindingSource.DataSource = myClassObjects;
dataGridView.DataSource = null;
dataGridView.DataSource = bindingSource;
dataGridView.Update();
dataGridView.Refresh();
我使用DataGridView的Invalidate()
函数。然而,这会刷新整个DataGridView。如果您想刷新特定行,则使用dgv.InvalidateRow(rowIndex)
。如果您想刷新特定单元格,则可以使用dgv.InvalidateCell(columnIndex, rowIndex)
。当然,前提是您使用绑定源或数据源。
private void RefreshGridView()
{
if (dataGridView1.InvokeRequired)
{
dataGridView1.Invoke((MethodInvoker)delegate ()
{
RefreshGridView();
});
}
else
dataGridView1.Refresh();
}
datagridview
的相同代码放入一个方法中,并将其传递给你的表单的datagridview
,如下所示:public void ConnectAndPopulateDataGridView(DataGridView dataGridView)
{ }
方法中的代码与用于填充datagridview
的代码完全相同,只是datagridview
的名称更改为您在方法中命名的任何内容。
现在,在您的父窗体中调用此方法。
子窗体通过.ShowDialog()
启动,然后在关闭子窗体后立即调用该方法...如下所示:
ChildForm.ShowDialog();
ConnectAndPopulateDataGridView(dataGridView1);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Table", conn))
{
DataTable dt = new DataTable();
ad.Fill(dt);
dataGridView1.DataSource = dt;
}
}
您只需要重新定义数据源。例如,如果您有一个包含a、b和c的DataGridView的DataSource:
DataGridView.DataSource = a, b, c
突然你更新了数据源,只剩下了a和b,你需要重新定义你的数据源:
DataGridView.DataSource = a, b
希望这对你有用。
谢谢。