-1

I am generating wpf form dynamically. All the controls are generated dynamically as follows

A sample code snippet

String tbname = name;
TextBlock txtBlock1 = new TextBlock();
txtBlock1.Text = tbname;

Grid.SetRow(txtBlock1, count);
Grid.SetColumn(txtBlock1, icount);
SampleGrid.Children.Add(txtBlock1);
TextBox txtBox = new TextBox();
txtBox.Text = ptiAttribute.description;
txtBox.Name = tbname.Replace(" ", "");
DynamicGrid.RegisterName(txtBox.Name, txtBox);
Grid.SetRow(txtBox, count);
Grid.SetColumn(txtBox, icount+1);
SampleGrid.Children.Add(txtBox);

Attaching a button click event as follows

var Button = CreateButton("Save", 15, 3);
Button.Click += new RoutedEventHandler(button_Click);
SampleGrid.Children.Add(Button);

I would like to get all the control values (For example: The above text box has value Book), I have to get it after button click. I am not only having text box. I have combo box, date picker too. I don't know which name is registered (RegisterName). Every thing dynamic.

private static void button_Click(object sender, RoutedEventArgs e)
{
   # How  to get dynamic values here (text bx value, date picker value, combo box value)
}

Simply, how to get values from dynamically generated controls. I have gone through a lot of Visual tree links but I don't know how it works on button click.

Any simple code snippet will help me to move ahead. Thanks

Sam
  • 5,040
  • 12
  • 43
  • 95

1 Answers1

1

I'm not used to WPF but try this approach(inspired by this):

private static void button_Click(object sender, RoutedEventArgs e)
{
   Button btn = (Button)sender; 
   int row = Grid.GetRow(btn);
   TextBox txtBox = SampleGrid.Children
      .OfType<TextBox>()
      .First(txt => txt.Name == name && Grid.GetRow(txt) == row);
   // ...
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • thanks for the immediate response. I ll check and update – Sam Nov 28 '17 at 13:33
  • The method does not know SampleGrid. This is underlined in my VS and the name is static it seems. – Sam Nov 28 '17 at 13:35
  • 1
    @Jefferson: well, you have used `SampleGrid` and the `name` variable in your code. So you know where it is – Tim Schmelter Nov 28 '17 at 13:45
  • @EdPlunkett - DataGrid is the original name but it found in another method, button_click does not know that – Sam Nov 29 '17 at 03:38
  • @EdPlunkett: what means it's found in another method? Is the button-click handler in the same class? Why you can't access the datagrid then? – Tim Schmelter Nov 29 '17 at 08:33