Search code examples
c#wpftextboxchildren

how to get value of last text box, that dynamically created


This code dynamically creates some text boxes. How to get value of 'last' text box in this UniformGrid? Web search did not make a good result!

Many thanks

       public Window1()
        {
            InitializeComponent();    
            for (var i = 0; i < 30; i++)
            {
                uniformGrid.Children.Add(new TextBox
                {
                    Width = 70,
                    Background = Brushes.Beige,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    Height = 30,                        
                    Margin = new Thickness(3)
                });
            }            
        }

Text boxes contains dates,I want to get last text box value and display in new text box with button event.

private void datePicker_SelectedDateChanged(object sender, RoutedEventArgs e)
        {
            DateTime a = DateTime.Parse(datePicker.Text);
            foreach (Control c in uniformGrid.Children)
            {
                TextBox textbox = c as TextBox;
                if (textbox != null)
                {
                    textbox.Text = a.ToString();
                    a = a.AddDays(1);
                }                
            }
        }


private void button_Click(object sender, RoutedEventArgs e)
{
lasttextBox =...
}

Solution

  • The last TextBox is going to be the last one you add and therefore the highest index value in the Children collection.

    int lastIndex = uniformGrid.Children.Count - 1;
    var lastBox = (TextBox)uniformGrid.Children[lastIndex];
    
    ResultTextBox.Text = lastBox.Text;
    

    In the event that you have other controls in there then you simply need to enumerate on only the text boxes (you could even save the result since you're doing the enumeration in the SelectedDateChanged event handler).

    TextBox lastBox = BoxGrid.Children.OfType<TextBox>().Last();
    ResultBox.Text = lastBox.Text;