locked
How to use VisualTreeHelper to get all TextBoxes

    Question

  • On the Page, I add UserControl into GridView dynamically. So, each UserControl can contain different kind of controls ( TextBox, CheckBox, Radio Button)

    How to get a collection of control of textbox  using VisualTreeHelper and check which textBox is empty.

    I found a code similiar to this problem and modified it but not working.

    I dont know what this means in the code and if it is required?

                list.AddRange(AllTextBoxes(child))

                Should I use MyList.Select() or MyList.Where() ?

    For example , the name of UserControl is : UserForm. This will be added into the GridView on the current page

    Thanks

    void FindTextBoxes()
    {

       List <TextBox> MyList = AllTextBoxes(UserForm);

       var count = MyList.Where(x= > if(string.IsEmptyOrNull(x.Text));

    }


    List <TextBox> AllTextBoxes(DependencyObject parent)
    {
        var list = new List <TextBox>();

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);

            if (child is TextBox)

                list.Add(child as TextBox);

            list.AddRange(AllTextBoxes(child));
        }
        return list;
    }

    Sunday, December 7, 2014 2:42 PM

Answers

  • Hi Machine7,

    Set a breakpoint after the AllTextBoxes() finishes and validate if all your textboxes are added into the list.

    I think there should be something wrong with your Linq, we can write it like this for your better understanding:

            void FindTextBoxes()
            {
    
                List <TextBox> MyList = AllTextBoxes(gridview);
    
                List<TextBox> emptyTextBox = new List<TextBox>();
                foreach (TextBox textbox in MyList)
                {
                    if (textbox.Text == "")
                    {
                        emptyTextBox.Add(textbox);
                    }
                }
    
               //var count = MyList.Where(x=>if(string.IsEmptyOrNull(x.Text));
    
            }

    If you still want to use Linq, try this:

     var t = MyList.Where(x => x.Text == "");

    --James


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by Machine7 Wednesday, December 10, 2014 1:18 PM
    Monday, December 8, 2014 6:46 AM
    Moderator