C# 从MySQL结果动态添加按钮、输入字段以形成表单

C# 从MySQL结果动态添加按钮、输入字段以形成表单,c#,mysql,winforms,compact-framework,C#,Mysql,Winforms,Compact Framework,例如,如果我在mysql数据库中有这个表 table: people id fname lname age profession 1 Gordon Batonvere 32 Teacher 2 Baron Greenstick 45 Engineer . . . 在表单上使用mysql,我可以得到以下结果: private void vie

例如,如果我在mysql数据库中有这个表

table: people
id        fname        lname        age        profession
1         Gordon       Batonvere    32         Teacher
2         Baron        Greenstick   45         Engineer
. . .
在表单上使用mysql,我可以得到以下结果:

private void viewFormOne_Load(object sender, EventArgs e)
        {
            string conn = "server=localhost;database=dbname;user=username;password=password;";


            MySqlConnection myconn = new MySqlConnection(conn);
            string sql = "SELECT * FROM `people`";
            MySqlDataAdapter da = new MySqlDataAdapter(sql, myconn);
            DataTable dt = new DataTable();
            try
            {
                da.Fill(dt);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("Sorry, there are no records to show.", "No Records");
            }
            else
            {
               //What to do here is what I don't know how to go about
            }
       }
如何在表单上显示该数据,如下所示:

NAME: Gordon Batonvere
AGE: 32

------------------------
| DISPLAY FULL PROFILE |    //This is a button
------------------------

.. ..  And so on

如何使标签和按钮动态显示

使用表单设计器向表单手动添加按钮,然后检查表单的designer.cs文件中生成的代码。这个过程非常简单——它需要创建一个button对象,设置它在表单中的位置,并将它分配给事件处理程序,以便在单击它时执行代码。下面是一个非常简单的例子:

    this.button1 = new System.Windows.Forms.Button();
    this.button1.Location = new System.Drawing.Point(86, 101);
    this.button1.Name = "button1";
    this.button1.Size = new System.Drawing.Size(75, 23);
    this.button1.TabIndex = 0;
    this.button1.Text = "button1";
    this.button1.UseVisualStyleBackColor = true;
    this.button1.Click += new System.EventHandler(this.button1_Click);

    private void button1_Click(object sender, EventArgs e)
    {

    }

标签和其他表单控件的过程非常相似。

我将创建一个自定义控件,因此您不必为每个条目分别创建和放置两个标签和文本框以及按钮。创建一个面板,并将标签、文本框和按钮放在上面。有两个公共属性来设置名称和年龄文本(或使用标签)。您甚至可以在添加新条目(自定义控件)时使用自定义类初始化器直接设置名称和年龄