简体   繁体   English

刷新BindingDataSource,上下文和控件的正确方法

[英]Proper way to refresh BindingDataSource, Context and Controls

This question may sound trivial but I'll ask it anyway. 这个问题听起来很琐碎,但我还是会问。 Given code below, what is the proper way to force ListBox to reflect new table content. 给定下面的代码,什么是强制ListBox反映新表内容的正确方法。

SQLDataContext dataContext = new SQLDataContext();
BindingDataSource myBindingDataSource = dataContext.MyTable1;
listBox1.DataSource = myBindingDataSource;
listBox1.DispalyMember = "Column1";
listBox.ValueMember = "Column2";

MyTable1 newRecord = new MyTable1();
newRecord.Column1 = "Some data";
newRecord.Column2 = 123;
dataContext.MyTable1.InsertOnSubmit(newRecord);
dataContext.SubmitChanges();

What is the most efficient way or best practice if you prefer, to force listBox1 into reflecting dataContext changes? 如果愿意,最有效的方法或最佳做法是强迫listBox1反映dataContext变化吗?

Please do not get offended but this is a classic example of misusing collections. 请不要生气,但这是滥用集合的经典示例。 You are using 2 parallel collections and you can't expect one to know much about one another unles they are properly linked. 您正在使用2个并行的集合,并且您不能期望他们对彼此正确链接的另一个对象了解很多。 Since you are binding listBox1 to BindingDataSource you should perform add, remove and update operations on the same BindingDataSource . 既然你要绑定listBox1BindingDataSource你应该执行添加,删除和更新操作在同一BindingDataSource It binds both ways. 它绑定两种方式。 Everything you add, update or delete from it will be reflected in bound controls and in the context. 您添加,更新或删除的所有内容都会反映在绑定的控件和上下文中。 Just submit context changes and you will update the database. 只需提交上下文更改,您将更新数据库。 In your example, you bypass BindingDataSource and write directly to the context so `BindingDataSource' has no idea about the change. 在您的示例中,您绕过BindingDataSource并直接写入上下文,因此“ BindingDataSource”不了解更改。

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

相关问题 如何以适当的方式添加动态控件? - How to add dynamic controls in proper way? 在Winform中访问用户控件的控件属性的正确方法是什么? - What is the proper way to access Controls properties of User Controls in Winform? 统一处理数据库上下文的正确方法 - Proper way of dispose a database context with unity WPF MVVM 中有没有办法刷新 TabControl 中的所有控件 - Is there a way in WPF MVVM to refresh all the controls within a TabControl 从列表中删除对象后刷新ObjectListView(TreeListView)的正确方法 - Proper way to refresh ObjectListView (TreeListView) after removing object from List 带有外键的DataGridView BindingDataSource - DataGridView BindingDataSource with a Foreign Key 如何将bindingdatasource转换为datatable? - How to cast bindingdatasource to datatable? 删除实体框架上下文中的所有记录并重新创建它的正确方法是什么? - What is the proper way to delete all records in an Entity Framework context and recreate it? 在树视图中指定数据上下文并绑定分层数据的正确方法是什么? - What is the proper way to designate the data context and bind hierarchical data in the treeview? 在允许双向绑定的用户控件中创建依赖项属性的正确方法是什么 - What is the proper way to create dependency properties in user controls that allow two way bindings
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM