2

ボタンのイベントハンドラー内で、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();

    }
4

3 に答える 3

2

namedynamic にaを付けます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 に答える