触发windows应用程序中动态创建的控件的单个事件

本文关键字:控件 单个 事件 创建 动态 windows 应用程序 触发 | 更新日期: 2023-09-27 18:15:23

我创建了一个在windows应用程序运行时创建一组控件的代码。我试图得到单个按钮的点击事件,但这是为所有的按钮工作。

我正在尝试的代码是

 public partial class Employee_PayHeads_add : Form
{

    private TextBox newTxtBox = new TextBox();
    private Button newBtnAdd = new Button();
    private ComboBox newCombohead = new ComboBox();
    private int txtBoxStartPosition = 150;
    private int btnAddStartPosition = 240;
    private int comboheadStartPosition = 10;

    private int txtBoxStartPositionV = 25;
    private int btnAddStartPositionV = 25;
    private int comboheadStartPositionV = 25;
    public Employee_PayHeads_add()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        TextBox newTxtBox = new TextBox();
        Button newBtnAdd = new Button();
        ComboBox newCombohead = new ComboBox();
        newBtnAdd.BackColor = Color.Gray;
        newBtnAdd.Text = "Remove";
        newBtnAdd.Location = new System.Drawing.Point(btnAddStartPosition, txtBoxStartPositionV);
        newBtnAdd.Size = new System.Drawing.Size(70, 25);
        newTxtBox.Text = "";
        newTxtBox.Location = new System.Drawing.Point(txtBoxStartPosition, btnAddStartPositionV);
        newTxtBox.Size = new System.Drawing.Size(70, 40);
        newCombohead.Location = new System.Drawing.Point(comboheadStartPosition, comboheadStartPositionV);
        panel1.Controls.Add(newBtnAdd);
        panel1.Controls.Add(newTxtBox);
        panel1.Controls.Add(newCombohead);

        txtBoxStartPositionV += 30;
        btnAddStartPositionV += 30;
        comboheadStartPositionV += 30;
        newBtnAdd.Click += new EventHandler(ButtonClick);

         }
    void ButtonClick(object sender, EventArgs e)
    {
        label1.Text = "Hello Gagan";
    }

我想获得单个按钮的单击事件,假设我必须在相应的文本框中显示文本,并在Label1上显示按钮。

触发windows应用程序中动态创建的控件的单个事件

我不知道你愿意做什么。无论如何,看看上面的代码,你可能有相当多的系列控件(按钮,然后是文本框,然后是组合框)都通过button1_Click()添加到面板中。如果是这种情况,遵循以下顺序:
  1. 从处理程序中,您将知道面板中按钮的索引。
  2. 下一个索引指向TextBox控件
  3. 获取文本框并设置文本

    void bu_Click(object sender, EventArgs e)
    {
        Type type = panel1.Controls[(panel1.Controls.IndexOf(sender as Button)) + 1].GetType();
        if(type == typeof(TextBox))
        {
            TextBox tb = (TextBox) panel1.Controls[
                            (panel1.Controls.IndexOf(sender as Button)) + 1];
            tb.Text = "Hello Gagan";
        }
    }