如何为表中的每个元素生成一个按钮?

时间:2017-01-25 09:25:20

标签: c# button

所以我想要做的是为表格中的每个员工生成一个按钮。例如,假设我的桌子上有四名员工,所以应该有四个按钮说“付款”。我已经包含了所需输出的屏幕截图。 我只是想不出任何想法这样做...任何人都可以帮助请或任何建议。 提前致谢。 我正在使用C#和visual studio Google Gson

3 个答案:

答案 0 :(得分:1)

假设您使用的是WinForms(?),您是否考虑过使用DataGridView控件? DataGridViewButtonColumn的列类型适合您的目的。创建一个表单,将DataGridView控件放到它上面并尝试这个演示代码:

using System;
using System.Data;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private System.Windows.Forms.DataGridViewButtonColumn ButtonColumn;
        private System.Windows.Forms.DataGridViewTextBoxColumn EmployeeColumn;

        public Form1()
        {
            //Add a DataGridView control to your form, call it "dataGridView1"
            InitializeComponent();

            EmployeeColumn = new System.Windows.Forms.DataGridViewTextBoxColumn()
            {
                Name = "Employee"
            };

            ButtonColumn = new System.Windows.Forms.DataGridViewButtonColumn()
            {
                Text = "Pay"
            };

            dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { EmployeeColumn, ButtonColumn });

            //Populate this as required
            var oDataTable = new DataTable();
            oDataTable.Columns.Add("Employee", typeof(String));

            dataGridView1.Rows.Add("Tom", ButtonColumn.Text);
            dataGridView1.Rows.Add("Dick", ButtonColumn.Text);
            dataGridView1.Rows.Add("Harry", ButtonColumn.Text);
        }
    }
}

答案 1 :(得分:0)

您可以执行类似伪代码的操作;

foreach(Employee emp in Employees)
{
  this.Controls.Add(//add label here with unique id)
  this.Controls.Add(//add button here with unique id)
}

*让我们假设Employees是Employee类型的集合 *您可能需要设置标签和按钮的位置,以便它们可以很好地显示在表单上。

答案 2 :(得分:0)

您可以轻松完成此操作。试试这样的事情 -

        private void Form1_Load(object sender, EventArgs e)
        {
            var employees = new string[] { "Emp1", "Emp2", "Emp3", "Emp4" }; 
            int btnTop = 0, btnLeft = 100, lblTop = 0, lblLeft = 20;

            foreach (var employee in employees)
            {
                btnTop += 30; lblTop += 30;
                this.Controls.Add(new Label { Text = employee, Left = lblLeft, Top = lblTop, Width = 50 });
                this.Controls.Add(new Button { Text = "Pay", Left = btnLeft, Top = btnTop, Width = 50 });
            }
        }

遍历您的员工表并添加您想要的任何控件。