I am working on WinForms UI and we have a requirement where we need to add repeating controls dynamically. I managed to create a UserControl with all labels and text boxes and adding them like this:
for (int i= 0; i < 4;i ++) {
tableLayoutPanel1.Controls.Add(new MyUserControl(),1,1);
//1,1 represent 1st row, 1st column of tablelayoutpanel
}
Now I am not able to find a way to bind different data to each control. For example: I need to display different contact information in each textbox every time a new user control is added. But since its the same UserControl, the textbox and labels have the same name and i am not sure how to bind different data using same UserControl.
I need something like this: I am able to add controls repeatedly, but not able to bind data: Screenshot
Any help would be greatly appreciated.
An Example of adding the
UserControl
to theTableLayoutPanel
Now you can use Tag Value to bind the data to the appropriate
UserControl
If you are creating custom user-controls. You can provide data-binding capabilities for your likes. You could use a parameter in the constructor to pass data in:
You can provide a property, to set the required data later:
You cold pass in a function to collect data:
Or some sort of service to retrieve the data:
If MyData implements INotifyPropertyChanged (or any custom event), you will be able react to data changes and display them. I guess you know how many controls need to be created. If yes, you know also why and which data you need provide.