【问题标题】:How to generate a button for every element in a table?如何为表格中的每个元素生成一个按钮?
【发布时间】:2017-06-10 09:49:48
【问题描述】:

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

【问题讨论】:

标签: c# button


【解决方案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);
        }
    }
}

【讨论】:

    【解决方案2】:

    你可以做类似下面的伪代码;

    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类型的集合 * 您可能需要设置标签和按钮的位置,以便它们在表单上显示得很好。

    【讨论】:

      【解决方案3】:

      您可以轻松做到这一点。试试这样的 -

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

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

      【讨论】:

        猜你喜欢
        • 2014-10-06
        • 1970-01-01
        • 1970-01-01
        • 2021-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多