按代码向我的表单添加按钮

时间:2015-07-24 17:46:32

标签: c# winforms button

我需要按代码创建x个按钮,并在加载表单时将它们放入groupBox中,每个按钮都有自己的点击和右键单击事件(contextMenuStrip)

我已经看到了有关动态添加按钮的其他问题,他们只允许创建固定数量的按钮,但对我来说,每次打开表单时该数字都会有所不同。

如果不可能,请告诉我另一种方法。

2 个答案:

答案 0 :(得分:1)

这是vb.net示例,但您可以使用一些在线转换工具轻松转换。

Dim lp As Integer = 0, tp As Integer = 0  'lp-left position, tp-top position in Your groupBox
For x = 1 to 20
 Dim btn As New Button
 btn.Name = "btn" + x.ToString
 btn.Text = x.ToString
 btn.Left = lp
 btn.Top = tp
 btn.Size = New Size(30, 30)
 AddHandler btn.Click, AddressOf btnClick
 groupBox.Controls.Add(btn)
 tp += btn.Height + 10
Next

Private Sub btnClick(sender As Object, e As EventArgs)
 Dim btn As Button = DirectCast(sender, Button)
 'for example
 If btn.Name = "btn1" Then
  'do something if You click on first button, ...
 End If
End Sub

这是如何动态创建20个按钮并将它们放入分组框的基本示例...所以您可以使用按钮的位置和大小。使用AddHandler您可以定义右键单击等等......您将看到所提供的内容。

在此示例中,按钮将被放置在另一个下面,依此类推。按钮文字将是数字。将此代码放在Form_Load

并且,当您在Form1_Load下打开表单时,您可以定义所需的按钮数量。

答案 1 :(得分:0)

在这个例子中(在LinqPAD上运行)我使用FlowLayout容器自动将按钮放在表单表面上,对于创建的每个按钮,我定义了一个按下按钮时应该执行的自定义动作

void Main()
{
    Form f = new Form();
    FlowLayoutPanel fp = new FlowLayoutPanel();
    fp.FlowDirection = FlowDirection.LeftToRight;
    fp.Dock = DockStyle.Fill;
    f.Controls.Add(fp);

    // Get the number of buttons needed and create them in a loop    
    int numOfButtons = GetNumOfButtons();
    for (int x = 0; x < numOfButtons; x++)
    {
        Button b = new Button();
        // Define what action should be performed by the button X
        b.Tag = GetAction(x);
        b.Text = "BTN:" + x.ToString("D2");
        b.Click += onClick;
        fp.Controls.Add(b);
    }
    f.ShowDialog();
}

// Every button will call this event handler, but then you look at the 
// Tag property to decide which code to execute
void onClick(object sender, EventArgs e)
{
    Button b = sender as Button;
    int x = Convert.ToInt32(b.Text.Split(':')[1]);
    Action<int, string> act = b.Tag as Action<int, string>;
    act.Invoke(x, b.Text);

}

// This stub creates the action for the button at index X
// You should change it to satisfy your requirements 
Action<int, string> GetAction(int x)
{
    return (int i, string s) => Console.WriteLine("Button " + i.ToString() + " clicked with text=" + s);
}

// Another stub that you need to define the number of buttons needed
int GetNumOfButtons()
{ 
    return 20;
}