For Each DataTable Add UserControl to FlowLayoutPa

2019-08-16 02:18发布

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条回答
你好瞎i
2楼-- · 2019-08-16 02:21

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);
    }
}
查看更多
登录 后发表回答