Binding data to an object - how to update an object / binding?

I got a text box and used data binding to the 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 need to clear the data binding and install it again after updating the product?

+4
source share
1 answer

In short: yes, you have to restore the DataBinding, because the TextBox has a reference to the old object.

But to make this a little more reliable, you might need to use a BindingSource for your DataBinding. For this to work, you must open the form in the design view.

  • Select your text block and open the Properties window.
  • Find the Data category and click on the cross to the left of the (DataBindings) property
  • Click the drop-down button next to the Text property
  • In the drop-down list, select Add project data source.
  • In the wizard, select Object and in the next type of your object

Now you will get a new object in your form (for example, productBindingSource) that is bound to the text of your TextBox. Last but not least, you must attach your object using the following code:

 productBindingSource.DataSource = product; 

But also this solution does not help in bandaging, but all you have to do is:

 product = new Product(); productBindingSource.DataSource = product; 
+8
source

Source: https://habr.com/ru/post/1312303/


All Articles