为每个 DataTable 添加 UserControl 到 FlowLayoutPanel [英] For Each DataTable Add UserControl to FlowLayoutPanel

查看:18
本文介绍了为每个 DataTable 添加 UserControl 到 FlowLayoutPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含图片和两个标签的 UserControl:标签名标签用户名

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

我还创建了一个从 SQL CE 数据库获取数据的 DataSet 和 DataTable.当我设法遍历所有 DataTable 行并在 MessageBox 中显示信息时,这一点工作正常.

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.

现在我想在 FlowLayoutPanel 中为 DataTable 中的所有行显示 UserControl,并使用 DataTable 中的 Name 和 Username 值填充两个标签.这就是我卡住的地方,因为我不知道在 UserControl 中编写什么代码以及在包含 FlowLayoutPanel 的表单中编写什么代码.

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.

有人可以帮帮我吗?

推荐答案

您可以在 Form 和 UserControl 中编写此代码.

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

在您的 UserControl 中,在属性或方法中公开两个标签中的每一个的 Text 属性.如果您选择一个属性,您的 Label labelUsername 可能看起来像这样:

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; }
}

在您的表单中循环遍历数据集中所有数据表中的所有数据行,并为每个数据行创建一个用户控件实例并将每个实例添加到您的 FlowLayoutPanel.在 DataRows 中使用适当的列值来设置 UserControl Label 值:

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);
    }
}

这篇关于为每个 DataTable 添加 UserControl 到 FlowLayoutPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆