简体   繁体   中英

Find a specific dynamic TextBox in a C# WPF GroupBox

I have added a GroupBox to my main Grid and am populating it dynamically with controls. I need to get a specific textbox within that GroupBox in an onClick event. I am able to loop through the GroupBox and fine, like this...

  foreach (Control ctl in ((Grid)gpMccEngineProperties.Content).Children)
  {
      if (ctl.GetType() == typeof(TextBox))
      {
          TextBox textbox = (TextBox)ctl;
          PropertyValue propertyValue = new PropertyValue();
          propertyValue.Value = textbox.Text;
      }
  }

... but if i just want to access a specific TextBox i keep coming back with a null value. here is how i'm trying to get it...

TextBox txt = ((Grid)gpMccEngineProperties.Content).Children.OfType<TextBox>().Where(t => t.Name == "PropertyId_9") as TextBox;

... where PropertyId_9 is the name of a textbox that i added dynamically to the GroupBox. Any idea how i get that textbox so i can get it's value?

Thanks!

You're using the wrong Linq method. That code returns an IEnumerable of TextBoxes, not just the TextBox. Use Single or SingleOrDefault instead of Where:

TextBox txt = ((Grid)gpMccEngineProperties.Content).Children.OfType<TextBox>().Single(t => t.Name == "PropertyId_9");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM