简体   繁体   English

执行SQL查询后C#刷新/更新数据绑定控件

[英]C# Refresh/Update databound control after executing SQL query

I have a databound datagridview for a simple application. 我有一个用于简单应用程序的数据绑定datagridview。 I am using the built-in visual studio database, but am using SQL queries to manipulate the data as I prefer it. 我正在使用内置的Visual Studio数据库,但是正在使用SQL查询来按我喜欢的方式操作数据。 The datagrid view is only databound because it is a requirement. datagrid视图仅是数据绑定的,因为它是必需的。

After executing any the datagridview does not update by itself, however even after much research and testing everything I could find, nothing seems to work. 执行任何datagridview之后,它本身不会更新,但是即使经过大量研究和测试,我仍然可以找到所有东西,但似乎没有任何效果。 The data only updates after I restart the program. 重新启动程序后,数据才会更新。

This is what I currently have: 这是我目前拥有的:

dgvEmployee.DataSource = null;
dgvEmployee.Rows.Clear();
this.employeeBindingSource.ResetBindings(true);
dgvEmployee.DataSource = this.employeeBindingSource;

I know it is not the fault of my queries since opening the database shows the added values. 我知道这不是我的查询的错,因为打开数据库会显示添加的值。 Thank you for your time. 感谢您的时间。 This is my first question on this site so please go easy on me ;) 这是我在这个网站上的第一个问题,所以请对我轻松一点;)

Have you tried refreshing the main form UI right after? 之后您是否尝试过刷新主窗体UI? Something like this: 像这样:

dgvEmployee.DataSource = null;
dgvEmployee.DataSource = this.employeeBindingSource;
this.Refresh();
this.Update();

I am using this code and it is working well, but not sure if it is a best practice: 我正在使用此代码,并且运行良好,但是不确定这是否是最佳实践:

List<MyEmployeeData> lstDataSource = query.ToList();
dgvEmployee.DataSource = new BindingListView<MyEmployeeData>(lstDataSource);
dgvEmployee.Refresh();

It uses BindingListView class available via NuGet . 它使用可通过NuGet获得的BindingListView类

In your code theese two lines 在您的代码中,这两行

dgvEmployee.DataSource = null;
dgvEmployee.Rows.Clear();

are in my opinion not necessary. 我认为没有必要。

But you are missing something like this: 但是您缺少这样的东西:

this.employeeBindingSource.DataSource = tableWithNewData;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM