user9871834
user9871834

Reputation: 93

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!

Upvotes: 0

Views: 362

Answers (1)

JNP
JNP

Reputation: 131

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

Upvotes: 1

Related Questions