如何在更新后刷新c#dataGridView?

ame*_*mer 22 c# datagridview

我有一个dataGridView,当我点击任何行打开一个表格来更新行数据,但在结束更新后,更新表格被关闭,但dataGridView数据没有更新

我怎样才能做到这一点 ?

Coo*_*ops 38

BindingSource是没有第三方ORM的唯一方法,它起初可能看起来很长,但一种更新方法的好处BindingSource是如此有用.

如果您的来源是例如用户字符串列表

List<string> users = GetUsers();
BindingSource source = new BindingSource();
source.DataSource = users;
dataGridView1.DataSource = source;
Run Code Online (Sandbox Code Playgroud)

那么当你完成编辑只需更新您的数据对象不管是一个DataTable用户字符串或列表就像这里ResetBindings的BindingSource;

users = GetUsers(); //Update your data object
source.ResetBindings(false);
Run Code Online (Sandbox Code Playgroud)

  • ResetBindings似乎只适用于.net类型.我想如果你使用自定义集合,你需要实现IBindingList接口,但我还没有尝试过. (3认同)

Ian*_*Ian 31

将DatagridView重新绑定到源.

DataGridView dg1 = new DataGridView();
dg1.DataSource = src1;

// Update Data in src1

dg1.DataSource = null;
dg1.DataSource = src1;
Run Code Online (Sandbox Code Playgroud)


小智 7

我知道这是一个老话题,但我突然找到了最好的方法,它不需要取消数据源并重新分配它。只需使用 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

}
Run Code Online (Sandbox Code Playgroud)