duykhoa
duykhoa

Reputation: 2302

Get text of a text box that was created at runtime

In my app, I create a text box at the runtime, here is the code

TextBox bt = new TextBox();
bt.Name = "population_textbox";
bt.Height = 20;
bt.SetValue(Grid.ColumnProperty, 1);
bt.SetValue(Grid.RowProperty, 0);
temp_grid.Children.Add(bt);

So, how to get the Text of this text box after user type something and enter. I don't know how to do it, I try

var tb = (FrameworkElement)this.FindName("population_textbox") as TextBox;
Console.Write(tb.Text);

And this is the error alert:

Exception has been thrown by the target of an invocation.

Upvotes: 0

Views: 279

Answers (3)

user1064519
user1064519

Reputation: 2190

you should declare your control and then call RegisterName method that makes the control accessible, then you can refer to the control name from anywhere in your window scope:

        TextBox bt = new TextBox();
        bt.Name = "population_textbox";
        bt.Height = 20;
        bt.SetValue(Grid.ColumnProperty, 1);
        bt.SetValue(Grid.RowProperty, 0);
        temp_grid.Children.Add(bt);
        this.RegisterName(bt.Name, bt);


        var tb = this.FindName("population_textbox") as TextBox;
        Console.Write(tb.Text);

Upvotes: 1

Freelancer
Freelancer

Reputation: 9074

Use following code:

 this.RegisterName("bt", textBox);

Also try:

var tb = (FrameworkElement)this.FindName("population_textbox");

OR Directly write:

TextBox bt = new TextBox();
bt.Name = "population_textbox";
bt.Height = 20;
bt.SetValue(Grid.ColumnProperty, 1);
bt.SetValue(Grid.RowProperty, 0);
temp_grid.Children.Add(bt);
Console.Write(bt.Text);

[without taking it in tb var].

This is used to get the text from textbox whose value is assigned runtime.

Upvotes: 1

KF2
KF2

Reputation: 10153

I write an simple example for you:

 TextBox bt = new TextBox();
            bt.Name = "population_textbox";
            bt.Text = "some";
            bt.Height = 20;
            main_Grid.Children.Add(bt);
            foreach (TextBox txt in main_Grid.Children)
            {
                if (txt is TextBox)
                {
                    if ((txt as TextBox).Name == "population_textbox")
                    {
                        MessageBox.Show((txt as TextBox).Text);
                    }
                }
            }

Upvotes: 2

Related Questions