【问题标题】:Accessing Dynamically created control (textbox) in a dynamically created eventhandler在动态创建的事件处理程序中访问动态创建的控件(文本框)
【发布时间】:2014-03-16 17:03:40
【问题描述】:

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

     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();

    }

【问题讨论】:

  • 哦,谢谢@Selman22,太棒了!工作过
  • 在所以你感谢人们接受他们的回答哈哈

标签: c# .net eventhandler


【解决方案1】:

给你的动态TextBox一个name

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

然后:

void Myb_Clicked(object sender, EventArgs e) {

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

}

【讨论】:

  • @danish 是的,这种方式有什么问题?如果有多个文本框,您可以扩展这种方式。但是如果我们使用您的方式,那么我们需要知道编译时文本框的数量,我认为情况并非如此。
  • 字符串比较。我个人不喜欢它,事实证明它更慢。
  • 请注意您得到的是控件,而不是文本框。如果您需要 TextBox 特定属性,则需要先进行转换。此代码有效,因为 Text 恰好是 Control 类的属性。
  • @rene Text 属性定义在 Control 类中,因此它是所有 Form 控件的通用属性。但总的来说,你是对的。
  • 现在您已经编辑了您的评论,还有很多问题需要回答。您正在尝试使这个东西尽可能通用。拜托,即使有这样的思考过程,我也会说你错了。并不是说我通过避免字符串比较节省了宝贵的纳秒,但我发现你的方式完全错误。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您可以在课堂上保留对 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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-03
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多