How to get the value of textbox which is created at runtime in WPF

How to get the value of textbox which is created at runtime in WPF

I will show you how to add Controls at runtime and get their values in WPF.

1- Create WPF Application.
2- Add Button to add textbox at runtime.
3- Add Button to read value from textbox Which is Created at Runtime.
4- Add Stackpanel to Host Controls on it.

the following method Responsible for Add Controls at runtime:

private void AddTextboxes(int x)
{
  for (int i = 0; i < x; i++)
  {
  TextBox txtTest = new TextBox();
  Thickness txtThickness = new Thickness();
  txtTest.Name = "Textbox" + i;
  txtThickness.Left = 0;
  txtThickness.Top = 0;
  txtTest.Margin = txtThickness;
  txtTest.Width = 150;
  txtTest.Height = 25;

  //add Control to stack panel
  stackPanel1.Children.Add(txtTest);
  }
}

The following method Responsible for Read Values:

private void ReadValue()
{
  for (int i = 0; i < stackPanel1.Children.Count; i++)
  {
    if (stackPanel1.Children[i] is TextBox)
    {
    TextBox txtTest = (TextBox)stackPanel1.Children[i];
      if (! string.IsNullOrEmpty(txtTest.Text))
      {
      MessageBox.Show(txtTest.Text);
      }
    }
  }
}

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *