![]() |
侠义非凡的苦瓜 · 中国汽车保有量首超3亿继续保持全球第一! ...· 4 周前 · |
![]() |
逆袭的移动电源 · 物理学院米文慧教授有关无轨道密度泛函理论系统 ...· 8 月前 · |
![]() |
坚强的汤圆 · 校草爱上花在线,漫画评分,在线评分 - 快看漫画· 1 年前 · |
![]() |
聪明的风衣 · 美人镜漫画|官方在线漫画全集-快看漫画· 1 年前 · |
![]() |
坚韧的马克杯 · 东城租房上学不占房东学位!北京海淀、西城明确 ...· 1 年前 · |
我有一个dataGridView,当我单击任何行时,表单将打开以更新行数据,但在结束更新后,更新表单将关闭,但dataGridView数据不会更新
我该怎么做呢?
将您的DatagridView重新绑定到源代码。
DataGridView dg1 = new DataGridView();
dg1.DataSource = src1;
// Update Data in src1
dg1.DataSource = null;
dg1.DataSource = src1;
BindingSource
是唯一不需要第三方ORM的方法,一开始可能看起来很冗长,但在
BindingSource
上使用一种更新方法的好处是非常有用的。
例如,如果您来源是用户字符串列表
List<string> users = GetUsers();
BindingSource source = new BindingSource();
source.DataSource = users;
dataGridView1.DataSource = source;
然后,当您完成编辑时,只需更新您的数据对象,无论是
DataTable
还是像
BindingSource
上的here和
ResetBindings
这样的用户字符串列表;
users = GetUsers(); //Update your data object
source.ResetBindings(false);
我不知道这个问题是否真的解决了..。但通过查看所有其他答案,似乎没有什么是非常清楚的。我找到的最好的方法是将用于填充
datagridview
的相同代码放入一个方法中,并将表单的
datagridview
传递给它,如下所示:
public void ConnectAndPopulateDataGridView(DataGridView dataGridView)
{ }
该方法中的代码与最初用于填充
datagirdview
的代码完全相同,只是
datagridview
名称更改为您在方法中调用的名称。
现在在父窗体中调用此方法。
通过
.ShowDialog()
启动子窗体,然后调用该方法,以便在关闭for的子窗体后立即调用该方法。因此:
ChildForm.ShowDialog();
ConnectAndPopulateDataGridView(dataGridView1);
您可以使用SqlDataAdapter更新DataGridView
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;
}
您可以使用DataGridView刷新方法。但是..。在许多情况下,您必须从运行DataGridView的线程之外的其他线程上运行的方法刷新DataGridView。为此,您应该实现以下方法并调用它,而不是直接键入DataGridView.Refresh():
private void RefreshGridView()
if (dataGridView1.InvokeRequired)
dataGridView1.Invoke((MethodInvoker)delegate ()
RefreshGridView();
dataGridView1.Refresh();
}
我知道我来晚了,但我希望这篇文章能帮助那些在类绑定方面也做同样事情的人
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();
我知道这是一个古老的话题,但我突然发现了最好的方法,它不需要取消数据源并重新分配它。只需使用BindingList而不是列表。
例如:
//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)