Tro*_*ond 4 .net c# data-binding winforms
我有一个文本框并使用数据绑定到一个对象.这很好,直到我尝试选择一个新产品:
product = new Product(id);
textbox.DataBindings.Add("Text", product, "ProductName");
// After user action:
product = new Product(newId); // <- the textbox isn't updated
Run Code Online (Sandbox Code Playgroud)
产品更新后,是否必须清除数据绑定并再次设置?
简而言之:是的,您必须重新建立DataBinding,因为TextBox具有对旧对象的引用.
但为了使其更加健壮,您应该为DataBinding使用BindingSource.要使其工作,您应该在设计视图中打开表单.
现在,您将在表单中获得一个新对象(例如productBindingSource),该对象绑定到TextBox的文本.最后但并非最不重要的是,您必须使用以下代码附加您的对象:
productBindingSource.DataSource = product;
Run Code Online (Sandbox Code Playgroud)
但是这个解决方案也不能帮助重新绑定,但你现在要做的就是:
product = new Product();
productBindingSource.DataSource = product;
Run Code Online (Sandbox Code Playgroud)