从事件处理程序获取表单中的动态控件

从事件处理程序获取表单中的动态控件

问题描述:

问题是如何在下面的代码中使用btncki_click中的txtcki文本:



the problem is how can i use txtcki text in btncki_click in below code:

public Form2()
        {
            int xllngth,loc=20;
             for (; ; xllngth++) 
             {                      
                    var buncoockie = new System.Windows.Forms.Button();
                    buncoockie.Name = "btncki" + xllngth;
                    buncoockie.Text ="cki"+ Convert.ToString(sheet1.Cells[xllngth, 2].value);
                    buncoockie.Size = new Size(100, 20);
                    buncoockie.Location = new System.Drawing.Point(145, loc);
                    buncoockie.BackColor = Color.AliceBlue;
                    buncoockie.Click += Btncki_Click;                                   
                    this.Controls.Add(buncoockie);
										
                   var txtcki=new System.Windows.Forms.TextBox();
                   txtcki.Name = "txtcki" + xllngth;
                   txtcki.Size = new Size(150, 20);
                   txtcki.Location = new System.Drawing.Point(245, loc);
                   this.Controls.Add(txtcki);                                      
                   loc += 20;
             }              
        }

        private void Btncki_Click(object sender, EventArgs e)
        {
           //string temp=txtcki.text;       
        }

首先,使用Button.Tag属性将它们绑定在一起:

First, use the Button.Tag property to tie them together:
var buncoockie = new System.Windows.Forms.Button();
buncoockie.Name = "btncki" + xllngth;
buncoockie.Text = "cki" + Convert.ToString(sheet1.Cells[xllngth, 2].value);
buncoockie.Size = new Size(100, 20);
buncoockie.Location = new System.Drawing.Point(145, loc);
buncoockie.BackColor = Color.AliceBlue;
buncoockie.Click += Btncki_Click;

var txtcki = new System.Windows.Forms.TextBox();
txtcki.Name = "txtcki" + xllngth;
txtcki.Size = new Size(150, 20);
txtcki.Location = new System.Drawing.Point(245, loc);

buncoockie.Tag = txtcki;
this.Controls.Add(buncoockie);
this.Controls.Add(txtcki);
loc += 20;



然后,在事件处理程序中:


Then, in the event handler:

private void Btncki_Click(object sender, EventArgs e)
    {
    Button buncoockie = sender as Button;
    if (buncoockie != null)
        {
        TextBox txtcki = buncoockie.Tag as TextBox;
        if (txtcki != null)
            {
            string temp = txtcki.text;
            ...
            }
        }
    }