0

我创建了一个代码,用于在运行时在 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 上的按钮在相应的文本框中显示文本。

提前致谢。

4

1 回答 1

0

我不知道你愿意做什么。不管怎样看上面的代码,你可能有很多串联的控件(按钮后跟文本框,然后是组合框)都通过 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";
        }
    }
    
于 2013-05-24T12:17:14.600 回答