2017-01-25 92 views
0

所以我想要做的是爲表中的每個員工生成一個按鈕。例如,假設我在我的表中有四名僱員,所以應該有四個按鈕說'付款'我已經包含了所需輸出的屏幕截圖。 我只是不能想出任何想法做到這一點...任何人都可以幫助請或任何建議。 在此先感謝。 我正在使用C#和visual studio enter image description here如何爲表中的每個元素生成一個按鈕?

+0

[如何將動態添加到我的窗體的可能的重複?](http://stackoverflow.com/questions/8608311/how-to-add-buttons-dynamically-to-my-form) –

+0

它在裏面顯示員工的循環,順便說一句,你到底做了什麼? –

+0

DataGridViewButtonColumn https://msdn.microsoft.com/en-us/library/bxt3k60s.aspx – Serg

回答

0

你可以做一些像下面的僞代碼;

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

*讓我們假設員工是Employee類型 集合*,使他們很好地出現在窗體上,您可能需要設置標籤和按鈕的位置。

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

循環訪問您的員工表並添加所需的任何控制。

相關問題