Hey,
I'm creating a little battleships game and it contains two 10*10 fields which itself contains 200 buttons. I'm creating them using the following code:
Later on, when the game has begun, I would want to find a specific button, and change it's color. In web application it could be done using ID and findControl:Code:private void battleField(int x, int y, int size, string shipName) { int pointA = 0; // first coordinate for (int i = 0; i < size * 10; i += size) { int pointB = 0; // second coordinate for (int t = 0; t < size * 10; t += size) { b1 = new Button(); b1.Location = new Point(x + t, y + i); b1.Size = new Size(size, size); b1.Name = (shipName + " " + System.Convert.ToString(pointA)+ " " + System.Convert.ToString(pointB)); b1.MouseUp += new MouseEventHandler(MainForm_MouseUp); b1.BackColor = customColor; this.Controls.Add(b1); pointB++; } pointA++; } }
Unfortunately this approach doesn't work in windows forms applications and I haven't found a good way to do it. I tried to do something like this, but I still can't get the specified button to change it's color.Code:Button x = (Button)Panel1.FindControl("f" + Convert.ToString(i)); x.BackColor = Color.Black;
Any help would be appreciated.Code:protected void changeColor(int x, int y, Color col) { foreach (Control c in this.Controls) { if (c.GetType() == typeof(Button)) { if (c.Tag == (System.Convert.ToString(x) + " " + System.Convert.ToString(y))) { c.BackColor = col; } } } }




Reply With Quote