2

我正在尝试在按钮的事件处理程序中访问我在 C# 中动态创建的文本框。

     void MainFormLoad(object sender, EventArgs e)
     {
        this.Width=600;
        this.Height=400;

        this.FormBorderStyle= FormBorderStyle.FixedDialog;
        TextBox t=new TextBox();
        this.Controls.Add(t);
        t.Location = new Point(60,40);
        Label Mylable=new Label();
        this.Controls.Add(Mylable);
        Mylable.Location=new Point(15,43);
        Mylable.Text="string : ";
        t.Width=200;
        t.Name="MyText";
        t.Refresh();
        Button Myb=new Button();
        Myb.Location=new Point(270,40);
        this.Controls.Add(Myb);
        Myb.Text="Reverse it!";
        Myb.Name="Mybo";
        Myb.Click += new EventHandler(this.Myb_Clicked);
        this.Refresh();                     
    }

    void Myb_Clicked(object sender, EventArgs e) {

              // HOW SHOULD I GAIN ACCESS to MyText.Text HERE
              MessageBox.Show();

    }
4

3 回答 3

2

name你的动态TextBox

 TextBox t=new TextBox();
 t.Name = "MyTextBox";
 this.Controls.Add(t);

接着:

void Myb_Clicked(object sender, EventArgs e) {

    string text = this.Controls["MyTextBox"].Text;

}
于 2014-03-16T17:05:25.530 回答
1

错误答案:object senderTextBox。您可以将发件人投射到文本框并使用它。

一个不错的方法是让您的文本框成为班级级别的成员。然后你就可以访问它了。如果没有,请链接TextBox.Text到字符串属性并使用它。

于 2014-03-16T17:09:04.307 回答
0

您可以在课堂上保留对 TextBox 的引用

 publc class MyForm: Form
 {

     TextBox myBox = null;  // class member

     void MainFormLoad(object sender, EventArgs e)
     {
         this.Width=600;
         this.Height=400;

         this.FormBorderStyle= FormBorderStyle.FixedDialog;
         TextBox t=new TextBox();
         myBox = t; // keep it for future reference

         // rest of your code
   }

   void Myb_Clicked(object sender, EventArgs e) {

          if (myBox !=null)
          {
                myBox.Text= "Clicked!";
          }
          MessageBox.Show();
    }
}
于 2014-03-16T17:14:43.383 回答