2

I need to use a single event handler for multiple buttons. I generated those buttons via while loop according to the database query. I created a single method

void MyButtonClick(object sender, EventArgs e)
{ 
}

I'm new to the C#. How can I bind all button's events to a single handler.

Code for generating the buttons:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {         
        try
        {
            MydbConnection db = new MydbConnection();
            MySqlConnection con = db.connection();
            MySqlCommand cmd = new MySqlCommand();

            cmd.CommandText = "select * from categories where online = 1";
            cmd.Connection = con;

            MySqlDataReader rd;
            con.Open();
            rd = cmd.ExecuteReader();

            int i = 1;
            while (rd.Read())
            {
                Button btn = new Button();
                btn.Name = "btn-" + i.ToString();
                btn.Tag = i;
                btn.Text = rd.GetString(2).ToString();

                btn.Height = 60;
                btn.Width = 100;
                btn.Location = new Point(900, 60 * i + 10);

                this.Controls.Add(btn);
                i++;
            }
        }
        catch (Exception ex) 
        {
            MessageBox.Show(ex.Message);
        }
    }
}

2 Answers 2

1

Welcome to SO. You can add this right before this.Controls.Add(btn);

btn.Click += MyButtonClick;
Sign up to request clarification or add additional context in comments.

2 Comments

How can I set btn.name into MyButtonClick().. pls
You can't set the name. because it's read only. I suspect you need to get the name, to know what button is clicked? If that's the case you can cast the sender object like this: var btn = (Button)sender and don't forget to check the null.
0

You need to set all of their CLICK properties to the same event handler:

btn.Click += new EventHandler(MyButtonClick);

That should make it so that anytime you click any of the buttons, MyButtonClick() is the event that triggers. Of course, if you need to figure out WHICH button was clicked, then you need to check the sender parameter within the event, where 'i' is one of the number values you assigned to a button in the loop:

(if sender == btn-i) then ....   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.