Reputation: 189
I need to create x number of buttons by code and place them into a groupBox when I load a form, each one with its own click and right click event (contextMenuStrip)
I've seen other questions about dynamically adding buttons here and they only allow a fixed number of buttons to be created but for me that number varies everytime I open the form.
If it is not possible please suggest me another way to do this.
Upvotes: 0
Views: 235
Reputation: 216353
In this example (run it on LinqPAD) I use a FlowLayout container to automatically put the buttons on your form surface and for every button created I define a custom action that should be performed when your button is pressed
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;
}
Upvotes: 0
Reputation: 4322
It's vb.net example but You can easy convert using some online converting tool.
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
This is basic example how to dynamically create 20 buttons and place them into groupbox... so You can do with position and size of button what You need. With AddHandler
You can define right click and so on... You'll see what's offered.
In this example, button will be placed one under other, and so on. Button text will be numbers. Put this code in Form_Load
.
And, when You open Your form under Form1_Load
You can define how many button You need.
Upvotes: 1