2013-04-08 41 views
0

建立在我的应用程序文本框中的文字,我创建在运行时的文本框,这里是代码获取通过在运行时

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

那么,如何得到这个文本框的文本后用户键入内容并输入。我不知道怎么办呢,我试着

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

这是错误警报:

Exception has been thrown by the target of an invocation. 
+0

Console.Write(((FrameworkElement的)这个.FindName(“population_textbox”)as TextBox).Text.ToString()); – zey 2013-04-08 09:15:40

+0

'temp_grid'是否有一个名为'FindName(..)'的方法?如果是,请尝试调用它而不是'this.FindName(..)' – 2013-04-08 09:16:12

+0

@zey:结果相同,异常已被抛出 – duykhoa 2013-04-08 09:19:23

回答

1

应声明你的控制,然后调用RegisterName方法,使控制访问,那么你可以参考该控件的名称从任何地方你的窗口范围:

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

我写一个简单的例子给你:

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); 
        } 
       } 
      } 
1

使用以下代码:

this.RegisterName("bt", textBox); 

也可以尝试:

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

或直接写信:

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

[没有考虑它在结核病变种。

这用于从文本框的文本中获取文本的值,该文本的值被赋值为运行时。

+0

你能给我一个完整的小例子吗?我是一个C新手# – duykhoa 2013-04-08 09:37:16

+0

@duykhoa通过我编辑的选择。 – Freelancer 2013-04-08 09:44:09

+0

我收到此异常消息:对象引用未设置为对象的实例。 – duykhoa 2013-04-08 09:54:58