from1中单击butten1,在from2上创建butten2和textbox2,再在butten2_Click事件中实,textbox2.Text=“aaaaa”;问题是在from2窗体上没有任何控件,怎么写单击事件的代码?我这样写的
        private void buttent2_Click(object sender, EventArgs e)
        {
            textbox2.Text = "aaa";
        }但是,提示错误,说上下文未定义textbox2,请问这样的问题怎么解决?

解决方案 »

  1.   

    你在from1中打开的Form2,并且创建的控件???
    那你应该在Form1中操作控件而不是Form2中
      

  2.   

    什么意思,button2和textbox2是动态创建的吗?想问什么?
      

  3.   

    是动态创建的,1楼的意思是说把Click事件的代码写到from1里是么?
    直接这么写?
     private void buttent2_Click(object sender, EventArgs e) 
            { 
                textbox2.Text = "aaa"; 
            } 
      

  4.   

    如果是动态创建的,那么就动态的创建事件不就行了,例如
    Button buttent2 = new Button();
    this.Controls.Add(button2);
    button2.Click +=new EventHandler(button2_Click);// 在添加事件之前textBox2必须已经创建出来了。
    ......private void buttent2_Click(object sender, EventArgs e) 
            { 
                textbox2.Text = "aaa"; 
            } 
    这样不就行了吗?
      

  5.   

    private TextBox txt;Button btn = new Button();
    btn.Name = "button2";
    .........
    btn.Click += new System.EventHandler(this.button2_Click);txt = new TextBox();
    txt.Name = "textbox2";
    ...........private void buttent2_Click(object sender, EventArgs e) 
            { 
                txt.Text = "aaa"; 
            } 
      

  6.   

    private void btnCreat_Click(object sender, EventArgs e)
            {
                Form2 frm = new Form2();
                Button btn = new Button();
                btn.Click += new EventHandler(btn_Click);//注册事件
                TextBox txtTest = new TextBox();
                txtTest.Name = "csdn";
                txtTest.Location = new Point(btn.Width,0);//调整位置
                frm.Controls.Add(btn);
                frm.Controls.Add(txtTest);
                frm.Show();
            }        void btn_Click(object sender, EventArgs e)
            {
                //找到btn所在窗体中的Name为csdn的TextBox的控件,赋值。
                ((TextBox)((Button)sender).Parent.Controls.Find("csdn", false)[0]).Text = "aaaaaaa";
            }