views:

38

answers:

1

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?

+2  A: 

In short: Yes, you have to re-establish the DataBinding, cause the TextBox has a reference to the old object.

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

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;
Oliver