【问题标题】:Removing dynamically generated buttons删除动态生成的按钮
【发布时间】:2013-09-10 21:38:07
【问题描述】:

我正在使用 C# windows 窗体,需要一些帮助。我有一个按钮可以创建其他按钮并将它们添加到列表“按钮”中。我需要让每个创建的按钮在单击时自行销毁。

        //create new button
        Button newButton = new Button();
        newButton.Name = "aButt"+buttNum;
        Debug.WriteLine(newButton.Name);
        buttNum++;

        newButton.Text = "Button!";
        newButton.Height = 50;
        newButton.Width = 50;

        //controls where the new button gets placed
        if (curX > 9)
        {
            curX = 0;
            curY++;
            //defines the point the button spawns
            newButton.Location = new System.Drawing.Point((curX * 55)+10, curY * 55);
            //increments X to avoid placing a button on top of another
            curX++;

        }
        else
        {
            newButton.Location = new System.Drawing.Point((curX * 55) + 10, curY * 55);
            curX++;
        }


        newButton.UseVisualStyleBackColor = true;
        newButton.Click += new System.EventHandler(this.removeThisButton);
        buttons.Add(newButton);
        this.Controls.Add(newButton);

我已经设置了事件监听器,但是由于发送者没有关于按钮本身的实际信息,我不知道如何摆脱它。

感谢任何帮助!

【问题讨论】:

  • 这是一个 Windows 窗体应用程序吗? WPF?我想添加更具体的标签以帮助吸引专家。

标签: c# winforms visual-studio


【解决方案1】:

点击事件处理程序有签名

private void myButton_Click(object sender, EventArgs e)

object sender 是事件的来源。只需将其转换为 Button,然后点击即可:

    Button whatWasClicked = sender as Button;
    if(whatWasClicked == null)
        // never mind -- it wasn't a button...

【讨论】:

  • 你可以,但是从任何地方调用这个方法,不一定是一个按钮。最好检查并确保发件人是按钮。
  • 确实如此。已更新。
【解决方案2】:

发件人是按钮。您可以像这样从 Form 的控件集合中删除它:

private void removeThisButton(object sender, EventArgs e) {
    this.Controls.Remove(sender);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 2011-05-13
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    相关资源
    最近更新 更多