多个GroupBox中每个按钮的Button_click事件(代码中)

本文关键字:事件 click 代码 GroupBox 按钮 多个 Button | 更新日期: 2023-09-27 17:59:15

我有多个groupbox,其中一个包含一个问题和一些答案,每个GroupBox中都有button答案。我在Form_Load方法中创建GroupBox及其控件,而不是手动创建。如何为每个button处理button_click事件?我认为没有必要为每个button编写这个句柄方法,因为只有两个不同的button_handler:对于只有一个正确答案的问题,以及对于多个答案可以正确的问题。我的问题看起来像:

我的GroupBox结构:

int loc = 20;
            for (int i = 0; i < 10; i++)
            {
                GroupBox gb = new GroupBox();
                gb.Name = "GroupBox" + (i + 1);
                gb.Size = new Size(500, 200);
                gb.Location = new Point(40, loc);
                gb.BackColor = System.Drawing.Color.Aquamarine;
                Label q_text = new Label(); // текст питання
                q_text.Name = "label" + (i + 1);
                q_text.Text = "Питання" + (i + 1);
                q_text.Font = new Font("Aria", 10, FontStyle.Bold);
                q_text.Location = new Point(10, 10);
                gb.Controls.Add(q_text);
                int iter = q_text.Location.Y + 30;
                if (i <= 5)
                {
                    foreach (string key in questions[i].answers.Keys)
                    {
                        RadioButton rb = new RadioButton();
                        rb.Text = key;
                        rb.Size = new Size(120, 25);
                        rb.Location = new Point(q_text.Location.X + 10, iter);
                        iter += 30;
                        gb.Controls.Add(rb);
                    }
                }else
                    if (i > 5)
                    {
                        foreach (string key in questions[i].answers.Keys)
                        {
                            CheckBox rb = new CheckBox();
                            rb.Text = key;
                            rb.Size = new Size(120, 25);
                            rb.Location = new Point(q_text.Location.X + 10, iter);
                            iter += 30;
                            gb.Controls.Add(rb);
                        }
                    }

                Button b = new Button();
                b.Name = "button" + (i + 1);
                b.Text = "Answer";
                b.Location = new Point(gb.Size.Width - 120, gb.Size.Height - 30);
                gb.Controls.Add(b);
                this.Controls.Add(gb);
                loc += 200;
            }

多个GroupBox中每个按钮的Button_click事件(代码中)

您可以为按钮创建一个常规点击事件:

Button b = new Button();
b.Name = "button" + (i + 1).ToString();
b.Click += b_Click;

在该方法中,检查发送者以查看点击了哪个按钮:

void b_Click(object sender, EventArgs e) {
  Button b = sender as Button;
  if (b != null) {
    GroupBox gp = b.Parent as GroupBox;
    int bIndex = Convert.ToInt32(b.Name.Substring(6)) - 1;
    MessageBox.Show(string.Format("I'm clicking {0}, question index #{1}",
                    gp.Name, bIndex));        
  }
}

之后,您必须检查GroupBox子控件的检查值以及questions[bIndex].answers变量中允许的答案。