【问题标题】:how to handle programmatically added button events? c#如何处理以编程方式添加的按钮事件? C#
【发布时间】:2011-01-07 10:32:13
【问题描述】:

我正在使用 C# 制作一个 Windows 窗体应用程序。我在运行时以编程方式添加按钮和其他控件。我想知道如何处理这些按钮的点击事件?

【问题讨论】:

    标签: c# dynamic controls


    【解决方案1】:

    试试下面的

    Button b1 = CreateMyButton();
    b1.Click += new EventHandler(this.MyButtonHandler);
    ...
    void MyButtonHandler(object sender, EventArgs e) {
      ...
    }
    

    【讨论】:

    • 谢谢,但它并不真正符合我的需要。我尝试根据您给我的内容搜索网络,但我找不到或理解任何内容。问题是,我有一系列按钮。我想知道点击了哪个按钮。
    • @jello,你有没有找到解决方案来确定点击了哪个按钮?我现在也有类似的问题。
    【解决方案2】:

    使用这段代码来处理几个按钮的点击事件:

        private int counter=0;
    
        private void CreateButton_Click(object sender, EventArgs e)
        {
            //Create new button.
            Button button = new Button();
    
            //Set name for a button to recognize it later.
            button.Name = "Butt"+counter;
    
           // you can added other attribute here.
            button.Text = "New";
            button.Location = new Point(70,70);
            button.Size = new Size(100, 100);
    
           // Increase counter for adding new button later.
            counter++;
    
            // add click event to the button.
            button.Click += new EventHandler(NewButton_Click);
       }
    
        // In event method.
        private void NewButton_Click(object sender, EventArgs e)
        {
            Button btn = (Button) sender; 
    
            for (int i = 0; i < counter; i++)
            {
                if (btn.Name == ("Butt" + i))
                {
                    // When find specific button do what do you want.
                    //Then exit from loop by break.
                    break;
                }
            }
        }
    

    【讨论】:

    • 谢谢贾米尔!它帮助了我的按钮数组案例。
    【解决方案3】:

    如果您想查看单击了哪个按钮,则可以在创建和分配按钮后执行以下操作。考虑到您手动创建按钮 ID:

    protected void btn_click(object sender, EventArgs e) {
         Button btn = (Button)sender // if you're sure that the sender is button, 
                                     // otherwise check if it is null
         if(btn.ID == "blablabla") 
             // then do whatever you want
    }
    

    您还可以检查它们是否为每个按钮提供命令参数。

    【讨论】:

      【解决方案4】:
      【解决方案5】:

      似乎这样有效,同时为数组的每个元素添加一个标签

      Button button = sender as Button;
      

      你知道更好的方法吗?

      【讨论】:

        【解决方案6】:

        关于您说您想知道单击了哪个按钮的评论,您可以将按钮的 .Tag 属性设置为您在创建和使用时想要的任何类型的标识字符串

        private void MyButtonHandler(object sender, EventArgs e)
            {
                string buttonClicked = (sender as Button).Tag;
            }
        

        【讨论】:

        • 至少这是我能想到的最简单的方法。
        猜你喜欢
        • 1970-01-01
        • 2013-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多