问题
I have one user control of size 25x25 and I want to duplicate it into three separate 10x10 grids which I can change the location of on my form. I'm making a pandemic simulation so the three grids represent the three countries and I will change the colour of the user control depending on the infection status of the grid square.
I've been playing around with this for a long time but I cannot get it to work, when I use Me.Controls.Add(UserControl) it overwrites the previous one and I'm left with only one user control on the form.
Any help appreciated, thanks.
回答1:
Below is a method that will create grid and you can place arbitrary controls into "cells" of this "grid". To run this, paste this code into any button handler and it will do everything it needs. I don't know if this is exact solution but you may get something out of it. It would be helpful if you could make a mock of your screen in different states, so we understand what you actually want.
Call method DoAGrid on some button handler:
DoAGrid(bool.Parse(_txtTest.Text)); // type true or false in txt
The methos
private void DoAGrid(bool isTest)
{
const int size = 30; // I give 2 for controll padding
const int padding = 20; // x and y starting padding
Point[,] grid = new Point[10,10]; // x and y of each control
List<Control> btns = null;
if (isTest) btns = new List<Control>(100);
for (int x = 1; x < 11; x++)
{
for (int y = 1; y < 11; y++)
{
grid[x - 1, y - 1] = new Point(padding + x*size - 30 - 1, padding + y*size - 30 - 1); // 30 - 1 --> size + 2
if (isTest)
{ // this test will add all avail buttons so you can see how grid is formed
Button b = new Button();
b.Size = new Size(size, size);
b.Text = "B";
b.Location = grid[x - 1, y - 1];
btns.Add(b);
}
}
}
Form f = new Form();
f.Size = new Size(1000, 1000);
if (isTest)
{
f.Controls.AddRange(btns.ToArray());
}
else
{
// Add controls to random grid cells
Button b1 = new Button();
b1.Size = new Size(size, size);
b1.Text = "B1";
b1.Location = grid[3, 3];
Button b2 = new Button();
b2.Size = new Size(size, size);
b2.Text = "B2";
b2.Location = grid[5, 5];
Button b3 = new Button();
b3.Size = new Size(size, size);
b3.Text = "B3";
b3.Location = grid[8, 8];
Button b4 = new Button();
b4.Size = new Size(size, size);
b4.Text = "B4";
b4.Location = grid[8, 9];
Button b5 = new Button();
b5.Size = new Size(size, size);
b5.Text = "B5";
b5.Location = grid[9, 8];
Button b6 = new Button();
b6.Size = new Size(size, size);
b6.Text = "B6";
b6.Location = grid[9, 9];
f.Controls.AddRange(new Button[] { b1, b2, b3, b4, b5, b6 });
}
f.ShowDialog();
}
来源:https://stackoverflow.com/questions/19711643/draw-three-grids-of-user-controls-in-vb-net