首页 > 解决方案 > 如何根据数据库结果动态添加面板

问题描述

如何根据从数据库获得的结果在其中动态添加面板和一些控件。 在此处输入图像描述

我想在面板中显示这个 datagridview 的结果,但是面板应该根据结果动态地相邻添加。就像我在 datagridview 中有 3 个结果一样,因此应该动态添加 3 个面板。请指教。

标签: c#sql

解决方案


您可以使用 aSqlConnection执行SELECT命令并获取所需的行并为每一行添加一个包含该行信息的自定义面板来实现此目的。
我还建议您使用 aFlowLayoutPanel以便它为您处理间距/位置。

在你的Form_Load

var conn = new SqlConnection("Your connection informations here");
conn.Open();

var command = new SqlCommand("Select * from YourTable", conn);

using (SqlDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        // Pass the useful informations to your panel
        var pnl = new MyCustomPanel(reader["Id"].ToString(), reader["Property_Type1"].ToString());
        flowLayoutPanel1.Controls.Add(pnl);
    }
}

conn.Close();

并且您的自定义控件的构造函数应该像这样,您可以在其中为每一行设置面板控件的值:

public MyCustomPanel(string id, string propertyType1)
{
    txtId.Text = id;
    txtPropertyType1.Text = propertyType1;
}

推荐阅读