| |

VerySource

 Forgot password?
 Register
Search
View: 696|Reply: 6

Problems loading buttons and loading events dynamically

[Copy link]

1

Threads

4

Posts

4.00

Credits

Newbie

Rank: 1

Credits
4.00

 China

Post time: 2020-2-17 20:00:01
| Show all posts |Read mode
Button a = null;
        public Form1 ()
        {
            InitializeComponent ();
        }

        private void Form1_Load (object sender, EventArgs e)
        {
            for (int i = 0; i <2; i ++)
            {
               a = new Button ();
                a.Text = i.ToString ();
                this.flowLayoutPanel1.Controls.Add (a);

                a.Click + = new System.EventHandler (this.button1_Click);
            }
        }

        private void button1_Click (object sender, EventArgs e)
        {
            MessageBox.Show (a.Text);
        }
  There are 2 buttons on the panel, but no matter which one you click, 2
   What I want to achieve is point 1 pop up 1 point 2 pop up 2
Reply

Use magic Report

1

Threads

7

Posts

5.00

Credits

Newbie

Rank: 1

Credits
5.00

 China

Post time: 2020-4-21 16:15:01
| Show all posts
a.Click + = new System.EventHandler (this.button1_Click); There is something wrong with this sentence.
There must be only one response
Reply

Use magic Report

1

Threads

4

Posts

4.00

Credits

Newbie

Rank: 1

Credits
4.00

 China

 Author| Post time: 2020-4-22 12:30:01
| Show all posts
What should I write to achieve it?
Reply

Use magic Report

0

Threads

8

Posts

8.00

Credits

Newbie

Rank: 1

Credits
8.00

 China

Post time: 2020-4-23 18:45:01
| Show all posts
private void button1_Click (object sender, EventArgs e)
{
Button clickedButton = sender as Button;
MessageBox.Show (clickedButton .Text);
}
Reply

Use magic Report

0

Threads

3

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

Post time: 2020-4-24 22:45:02
| Show all posts
You have implemented a dynamic loading button and support events, but the event handler is written wrong.

a is the object in the class instance, and the initial value is obtained outside the event handler function.
Reply

Use magic Report

1

Threads

4

Posts

4.00

Credits

Newbie

Rank: 1

Credits
4.00

 China

 Author| Post time: 2020-4-25 22:45:01
| Show all posts
yujunzilingThank you so much ~~
   private void button1_Click (object sender, EventArgs e)
    {
     Button clickedButton = sender as Button;
     MessageBox.Show (clickedButton .Text);
    }
 Right ~~
Reply

Use magic Report

1

Threads

4

Posts

4.00

Credits

Newbie

Rank: 1

Credits
4.00

 China

 Author| Post time: 2020-4-25 23:00:01
| Show all posts
Haha succeeded
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list