Timur Zanagar
Timur Zanagar

Reputation: 323

Best practice for User Control Data Binding - How to achieve this?

I've got an User Control with TextBoxes, Labels, ... . Now I would like to get the same Data Binding Features like I would place the Controls directly on the Form. I tried with an extra Binding Source and Error Provider in the User Control and I tried to make the Properties of my Controls available as an property.

Nothing worked. So there have to be an solution to get this done. So how?

Upvotes: 4

Views: 4647

Answers (1)

edymtt
edymtt

Reputation: 1808

I've realized a sample at https://github.com/edymtt/usercontrolwithdatabinding to illustrate some data binding scenarios that may apply to your question. In particular I've addressed two scenarios:

  1. Realization of an UserControl to edit a basic property (string, integer, ...);
  2. Realization of an UserControl to edit a property of a complex type (such as an Address POCO);

Realization of an UserControl to edit a basic property

In this case it suffices to expose the relevant property of an underlying control (for example the Text property of a TextBox) and to raise an appropriate event when this changes (continuing the example, handle the TextChanged event of the TextBox and raise a new TextChanged event, see this page on MSDN at the section "Change Notification for Custom Controls).

The ErrorProvider in the form (where you have the binding source) can handle this kind of UserControl without problem

Realization of an UserControl to edit a property of a complex type

This case is not much complex than the previous:

  • you need to put a BindingSource and an Error Provider in the usercontrol to handle the POCO you need;
  • next you need expose a property to receive the bound object and assign it at runtime.

I hope that the sample is clear enough to understand how the binding works.

Upvotes: 2

Related Questions