Create dynamic buttons in a grid layout - Create a magic square UI
You can use a TableLayoutPanel
and add buttons to panel dynamically.
If you don't need interaction with buttons, you can add Label
instead.
Create square dynamically:
public void CreateSquare(int size)
{
//Remove previously created controls and free resources
foreach (Control item in this.Controls)
{
this.Controls.Remove(item);
item.Dispose();
}
//Create TableLayoutPanel
var panel = new TableLayoutPanel();
panel.RowCount = size;
panel.ColumnCount = size;
panel.BackColor = Color.Black;
//Set the equal size for columns and rows
for (int i = 0; i < size; i++)
{
var percent = 100f / (float)size;
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, percent));
panel.RowStyles.Add(new RowStyle(SizeType.Percent, percent));
}
//Add buttons, if you have your desired output in an array
//you can set the text of buttons from your array
for (var i = 0; i < size; i++)
{
for (var j = 0; j < size; j++)
{
var button = new Button();
button.BackColor = Color.Lime;
button.Font = new Font(button.Font.FontFamily, 20, FontStyle.Bold);
button.FlatStyle = FlatStyle.Flat;
//you can set the text of buttons from your array
//For example button.Text = array[i,j].ToString();
button.Text = string.Format("{0}", (i) * size + j + 1);
button.Name = string.Format("Button{0}", button.Text);
button.Dock = DockStyle.Fill;
//If you need interaction with buttons
button.Click += b_Click;
panel.Controls.Add(button, j, i);
}
}
panel.Dock = DockStyle.Fill;
this.Controls.Add(panel);
}
If you need interaction with buttons
void button_Click(object sender, EventArgs e)
{
var button = (Button)sender;
//Instead put your logic here
MessageBox.Show(string.Format("You clicked {0}", button.Text));
}
As an example, you can call
CreateSquare(3);
Screenshot:
Arranging controls in Winforms TableLayoutPanel
Use the second overload of tableLayoutPanel1.Controls.Add() in order to pass the row and column index:public virtual void Add(Control control, int column, int row
);
EXAMPLE:
private void SetTableLayoutPanel()
{
tableLayoutPanel1.RowStyles.Clear();
tableLayoutPanel1.ColumnCount = 2;
tableLayoutPanel1.RowCount = 3;
tableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
var counter = 1;
for (int i = 0; i < tableLayoutPanel1.ColumnCount; i++)
{
for (int j = 0; j < tableLayoutPanel1.RowCount; j++)
{
Button b = new Button();
b.Text = "C" + counter;
tableLayoutPanel1.Controls.Add(b, i, j);
counter++;
}
}
}
OUTPUT:
Adding dynamic controls to TableLayoutPanel in .NET windows form
You just need to use the Controls.Add
method and specify column and row for the control:
rowLayout.Controls.Add(tb1, 0, 0);
rowLayout.Controls.Add(tb2, 0, 1);
C# winforms add controls to dynamic created tabpages
I think the previous statement regarding the placement of the buttons is probably the problem. Try adding the following which will change the placement of each button.
int i = 0;
while (reader.Read())
{
Button btn = new Button();
string name = reader["name"].ToString();
btn.Text = name;
btn.Name = "desk_" + reader["id"];
btn.Size = new Size(100, 60);
btn.Location=new Point(100, 100+i);
desk.Add(btn);
i += 10;
}
Dynamically assign a click event to every single button located in a grid cell
every C# event handler has a sender parameter that is a reference to the object that fired the event
protected void ButtonClicEvent(object sender, EventArgs e)
{
var btn = (Button)sender;
// btn is a reference to the button that fired the event
btn.BackgroundColor = Color.Orange;
}
Related Topics
Why Isn't Arraylist Marked [Obsolete]
Event Bubbling and Mvp: ASP.NET
Model-View-Presenter in Winforms
How to Access Configuration in Any Class in ASP.NET Core
How to Merge 2 List<T> and Removing Duplicate Values from It in C#
Multiple Colors in a C# .Net Label
Path.Combine Absolute with Relative Path Strings
Why Can't I Access C# Protected Members Except Like This
Convert Binary String into Integer
String Concatenation VS String Builder. Performance
Why Doesn't Xmlserializer Support Dictionary
What Is the Fastest Way to Create a Checksum for Large Files in C#
Httpclient Not Supporting Postasjsonasync Method C#
How to Use the C#6 "Using Static" Feature
How to Convert Datetime To/From Specific String Format (Both Ways, E.G. Given Format Is "Yyyymmdd")