For Each DataTable Add UserControl to FlowLayoutPanel

天涯浪子 提交于 2019-12-24 20:18:14

问题


I have created a UserControl which has a picture and two labels: labelName labelUsername

I have also created a DataSet and DataTable which gets the data from a SQL CE database. This bit is working fine as I managed to loop through all the DataTable rows and display the information in a MessageBox.

Now I want to display the UserControl in a FlowLayoutPanel for all rows in the DataTable and populate the two labels with the Name and Username values from the DataTable. This is where I am stuck as I don't know what to code in the UserControl and what to code in the Form that contains the FlowLayoutPanel.

Can someone help me out please?


回答1:


You'd code this in both your Form and your in UserControl.

In your UserControl expose the Text property of each of your two Labels in a property or a method. If you choose a property, it might look something like this for your Label labelUsername:

public string Username {
    set { labelUsername.Text = value; }
}

In your Form loop through all DataRows in all DataTables in your DataSet and for each DataRow create an instance of your UserControl and add each to your FlowLayoutPanel. Use the appropriate column values in your DataRows to set your UserControl Label values:

foreach (DataTable dt in ds.Tables) {
    foreach (DataRow row in dt.Rows) {
        var uc = new YourUserControl { Username = row["usernameColumn"].ToString(), 
                                       Name = row["nameColumn"].ToString() };
        flowLayoutPanel1.Controls.Add(uc);
    }
}


来源:https://stackoverflow.com/questions/12589810/for-each-datatable-add-usercontrol-to-flowlayoutpanel

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