简体   繁体   English

10x10的100个按钮网格:单击时隐藏按钮(C#)

[英]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. 我有100个按钮的10x10网格,我想在单击按钮时隐藏它。

Is there a way to apply this to all buttons?? 有没有办法将其应用于所有按钮? ie When any of the button is clicked then that button is hidden. 即,当单击任何按钮时,该按钮将被隐藏。 I use a table layout to arrange the 100 buttons in C#. 我使用表格布局来排列C#中的100个按钮。

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) 我也将它添加到表格布局中,所以请告诉我如何将这些按钮添加到该10x10表格网格中。在这里,如何命名按钮对象以及如何添加单个事件来对自身执行所有操作(即在单击时隐藏自身) )

Create 100 buttons 创建100个按钮

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. 在事件处理程序中,将sender投射到Button ,这就是按下的特定按钮。

Since you are using tablelayoutpanel, you don't need to calculate positions for the buttons, the control is doing it for you. 由于您使用的是tablelayoutpanel,因此不需要计算按钮的位置,因此控件正在为您完成操作。 You can also set the buttons dock property to be fill, so you don't need to setup size of the buttons. 您还可以将按钮停靠属性设置为fill,因此您无需设置按钮的大小。 All you'll have to do is to setup the properties of the tableLayoutPanle 您要做的就是设置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);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM