Binding data to controls in a Repeating user control with c#/WinForms

Siri

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.

Sven Bardos

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:

public MyUserControl(MyData mydata):this()
{ ...
}

You can provide a property, to set the required data later:

public class MyUserControl()
{ 
   ...
   public MyData MyDataSource {get;set;}
}

You cold pass in a function to collect data:

 public MyUserControl(func<MyData> mydata):this()
 { 

 }

Or some sort of service to retrieve the data:

 public MyUserControl(IMyService myService):this()
 {
    Textbox1.Text = myService.GetImportantText();
 }

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related