问题描述
我有一个文本框,并使用数据绑定到一个对象。这工作得很好,直到我尝试选择新的产品:
I got a textbox and use databinding to an object. This works fine, until I try to select a new product:
product = new Product(id);
textbox.DataBindings.Add("Text", product, "ProductName");
// After user action:
product = new Product(newId); // <- the textbox isn't updated
我必须清除数据绑定和重新设置后,产品的更新?
Do I have to clear the databinding and set it again after the product is updated?
推荐答案
简而言之:是的,你必须要重新建立数据绑定,使文本框引用了旧的对象
In short: Yes, you have to re-establish the DataBinding, cause the TextBox has a reference to the old object.
但是,为了使这一点更强大的,你也许应该使用的BindingSource您的数据绑定。为了得到这个工作,你应该在设计视图中打开窗体。
But to make this a little more robust, you should maybe use a BindingSource for your DataBinding. To get this to work, you should open your form in design view.
- 选择您的文本框,并打开属性窗口
- 查找到类别数据,然后点击在十字架上的左边(数据绑定)属性
- 点击下拉按钮旁边的文字属性
- 在下拉列表中选择添加项目数据源
- 从向导中选择对象,并在接下来的对象类型
- Select your TextBox and open the Properties window
- Look into category Data and click on the cross to the left of the (DataBindings) property
- Click on the drop down button next to the Text property
- In the drop down list select Add project data source
- From the wizard select Object and in the next your object type
现在你会得到一个新的对象,在你的形式(如 productBindingSource 的),绑定到你的文本框的文本。最后但并非最不重要的,你必须使用以下code附上你的对象:
Now you'll get a new object in your form (e.g. productBindingSource), that is bound to the text of your TextBox. Last but not least you have to attach your object by using the following code:
productBindingSource.DataSource = product;
而且这种解决方案并不反对重新绑定帮助,但你现在要做的是:
But also this solution doesn't help against a re-binding, but all you have to do now is:
product = new Product();
productBindingSource.DataSource = product;
这篇关于数据绑定对象 - HOWTO更新对象/绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!