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

人盡茶涼 提交于 2019-12-12 01:27:24

问题


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.


回答1:


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.




回答2:


An Example of adding the UserControl to the TableLayoutPanel

for (int nCount = 0; nCount < 2; nCount++)
{
   CheckUserControl uc = new CheckUserControl();
   //If required Assign Value to the control
   uc.strValue = "Item " + nCount;
   uc.strTag = nCount.ToString();
   //You can pass the Column and Row value dynamically
   tableLayoutPanel1.Controls.Add(uc, 1, 1);
}

Now you can use Tag Value to bind the data to the appropriate UserControl



来源:https://stackoverflow.com/questions/54137475/binding-data-to-controls-in-a-repeating-user-control-with-c-winforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!