0

I have a stackpanel with dynamically created textboxes and buttons in my wpf application. This works ok. Later in the application I have to use the name of the textboxes and the values. How do I do that. I have this code: First the creation of the textboxes i a stackpanel named panelBet.

Second a switch-case where the name and the value is used. Red lines under 'controls'.

First creation:

int f = 1;
foreach (TextBox txt2 in txtBet)
{
    string name = "Bet" + f.ToString(); ;

    txt2.Name = name;
    txt2.Text = name.ToString();
    txt2.Width = 100;
    txt2.Height = 40;
    txt2.Background = Brushes.Lavender;
    txt2.Margin = new Thickness(3);
    txt2.HorizontalAlignment = HorizontalAlignment.Left;
    txt2.VerticalAlignment = VerticalAlignment.Top;
    txt2.Visibility = Visibility.Visible;

    panelBet.Children.Add(txt2);

    f++;
}

Second switch-case:

private void cboRunder_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var cboRunder = sender as ComboBox;

    string strRunder = cboRunder.SelectedValue.ToString(); // blinds, preflop osv.

    switch (strRunder)
    {
        case "Blinds":
            string s = ((TextBox)panelBet.Controls["txtBet"]).Text;                 
    }
}
Ryan Thomas
  • 1,724
  • 2
  • 14
  • 27
  • I would use [WPF binding mvvm StackPanel](https://stackoverflow.com/questions/10825789/wpf-binding-mvvm-stackpanel). Then you don't need to access the StackPanel and to create or read the TextBoxes at all. Instead, you can access the data directly from your collection. Just add TextBox instead of Label as in the linked example – Olivier Jacot-Descombes Feb 01 '23 at 14:16
  • If you're dynamically creating these controls, why not keep a reference to them in a more convenient sort of structure than deep in the UI tree? Like a List, dictionary or something. Or better still, template out viewmodel(s) into these controls and work with data in the viewmodels. – Andy Feb 01 '23 at 16:06

1 Answers1

1

This should get you a reference to the TextBox named "txtBet" in the panelBet assuming there is one:

TextBox txtBet = panelBet.Children.OfType<TextBox>()
    .FirstOrDefault(x => x.Name == "txtBet");
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
mm8
  • 163,881
  • 10
  • 57
  • 88