Suraj
Suraj

Reputation: 96

10x10 grid of 100 buttons: hiding a button on click (C#)

I have a 10x10 grid of 100 buttons, I want to hide a button when it is clicked.

Is there a way to apply this to all buttons?? i.e. When any of the button is clicked then that button is hidden. I use a table layout to arrange the 100 buttons in C#.

also im adding it to table layout so kindly tell me how to add these buttons to that 10x10 table grid..here how will the button objects be named and how to add individual events all performing the action to itself(that is hide itself when clicked)

Upvotes: 0

Views: 2170

Answers (2)

Gorgi Rankovski
Gorgi Rankovski

Reputation: 2313

Since you are using tablelayoutpanel, you don't need to calculate positions for the buttons, the control is doing it for you. You can also set the buttons dock property to be fill, so you don't need to setup size of the buttons. All you'll have to do is to setup the properties of the tableLayoutPanle

So..

Button b;
foreach (int i in Enumerable.Range(0, 100))
{

        b = new Button();
        //b.Size = new System.Drawing.Size(20, 20); 
        b.Dock = DockStyle.Fill
        b.Click += new EventHandler(anyButton_Click); // <-- all wired to the same handler
        tableLayoutPanel.Controls.Add(b);

}

Upvotes: 0

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47058

Create 100 buttons

foreach (int i in Enumerable.Range(0, 10))
{
    foreach (int j in Enumerable.Range(0, 10))
    {
        Button b = new Button();
        b.Size = new System.Drawing.Size(20, 20);
        b.Location = new Point(i * 20, j * 20);
        b.Click += new EventHandler(anyButton_Click); // <-- all wired to the same handler
        this.Controls.Add(b);
    }
}

and connect them all to the same event handler

void anyButton_Click(object sender, EventArgs e)
{
    var button = (sender as Button);
    if (button != null)
    {
        button.Visible = false;
    }
}

in the eventhandler you cast sender to Button and that is the specific button that was pressed.

Upvotes: 9

Related Questions