动态生成几个控件,并且为他们的name属性赋不同的值储存在list<>集合中。怎样才能点击他们,然后就显示控件自己的name属性在 textbox 里。我每次点击都是显示最后创建一个控件的name属性,无论单击哪个都是显示最后创建一个的name属性。
很烦恼啊!

解决方案 »

  1.   

    贴代码。另:
    你为什么不在List<>集合里存名称而不存控件本身呢?难道怕把List<>撑破了?
      

  2.   


    我的确是存控件实例的。  public partial class Form1 : Form
        {
            List<Collect> list = new List<Collect>();
            Collect collect;
            public Form1()
            {
                InitializeComponent();
            }        private void button1_Click(object sender, EventArgs e)
            {
                if (list.Count == 0)
                {
                    collect = new Collect();
                    collect.Location = new Point(10, 10);
                    collect.Name = textBox1.Text;
                    collect.URL = textBox2.Text;
                    collect.Click += new EventHandler(collect_Click);
                    this.Controls.Add(collect);
                    list.Add(collect);
                    collect.suoy = list.IndexOf(collect);
                   
                }
                else
                {
                    collect = new Collect();
                    int y = list.Last<Collect>().Location.Y;
                    y += 30;
                    collect.Location = new Point(10, y);
                    collect.Name = textBox1.Text;
                    collect.URL = textBox2.Text;
                    collect.Click += new EventHandler(collect_Click);
                    this.Controls.Add(collect);
                    list.Add(collect);
                    collect.suoy = list.IndexOf(collect);
                }
                
            }        void collect_Click(object sender, EventArgs e)
            {
                textBox3.Text = collect.Name;
            }    }
        public class Collect : Button
        {
            public string URL { get; set; }
            public int suoy { get; set; }
     
        }Collect类是自己写的,继承Button。因为我要加两个属性。
    可以把collect当button类来看。
      

  3.   

    修改如下  void collect_Click(object sender, EventArgs e)
            {
                textBox3.Text = (sender as Button).Name;
            }
      

  4.   

    嗯,既然楼主没有具体的代码,我写个例子,看看能不能有帮助.
    //控制集合
    List<Control> lst = new List<Control>();
    //创建3个button 
    for(int i=1;i<4;i++)
    {
      Button b = new Button();
      b.Name = "button"+ i.ToString();
      lst.Add(b);
    }//获取name为button2的按钮
    Button b = lst.Find(x=>x.Name=="button2") as Button;
    MessageBox.Show(b.Name);
      

  5.   


    将当前触发事件的控件转换为Button,因为你添加的就是Button