how to handle programmatically added button events? c#

前端 未结 6 1749
悲哀的现实
悲哀的现实 2020-12-03 07:39

I\'m making a windows forms application using C#. I add buttons and other controls programmatically at run time. I\'d like to know how to handle those buttons\' click events

6条回答
  •  星月不相逢
    2020-12-03 08:22

    Use this code to handle several buttons' click events:

        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;
                }
            }
        }
    

提交回复
热议问题