c# - 数据绑定(bind)到对象 - 如何更新对象/绑定(bind)?

标签 c# .net winforms data-binding

我有一个文本框并使用数据绑定(bind)到一个对象。这工作正常,直到我尝试选择一个新产品:

product = new Product(id);
textbox.DataBindings.Add("Text", product, "ProductName");

// After user action:
product = new Product(newId); // <- the textbox isn't updated

是否必须在产品更新后清除数据绑定(bind)并重新设置?

最佳答案

简而言之:是的,您必须重新建立 DataBinding,因为 TextBox 具有对旧对象的引用。

但是为了使它更健壮一些,您也许应该为您的 DataBinding 使用 BindingSource。要使其正常工作,您应该在设计 View 中打开表单。

  • 选择您的文本框并打开“属性”窗口
  • 查看类别Data 并单击(DataBindings) 属性左侧的叉号
  • 点击文本属性旁边的下拉按钮
  • 在下拉列表中选择添加项目数据源
  • 从向导中选择对象,然后在接下来选择您的对象类型

现在您将在表单中获得一个新对象(例如 productBindingSource),该对象绑定(bind)到您的 TextBox 的文本。最后但同样重要的是,您必须使用以下代码附加您的对象:

productBindingSource.DataSource = product;

但此解决方案也无助于重新绑定(bind),但您现在要做的是:

product = new Product();
productBindingSource.DataSource = product;

关于c# - 数据绑定(bind)到对象 - 如何更新对象/绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3004731/

相关文章:

.net - 使 WebBrowser 控件删除其缓存

c# - 如何禁用 WinForms 中 TreeView 的节点重命名?

c# - 包装 INLINE 函数

c# - EF linq,删除所有相关的OwnerId到Id

.net - 通过 ADO.Net 和 COM 互操作性进行 MS Access 批量更新

c# - 将树结构解析为 If 语句

C# Winforms-WPF 互操作

c# - C# 中的 wtol 等价物

c# - .NET Core 应用程序调试错误 : "Unable to set the next statement. This file does not exactly match the original version."

c# - 在大型项目中使用命名空间是否有任何指导方针?