【问题标题】:Dynamically Add Buttons, Input Fields to Form from MySQL Result从 MySQL 结果动态添加按钮、输入字段到表单
【发布时间】:2014-11-04 21:53:45
【问题描述】:

例如,如果我在 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

如何让标签和按钮动态显示?

【问题讨论】:

    标签: c# mysql winforms compact-framework


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-30
        • 1970-01-01
        • 1970-01-01
        • 2016-05-07
        • 1970-01-01
        • 2017-05-06
        • 1970-01-01
        • 2012-08-17
        相关资源
        最近更新 更多