ASP.Net Accessing child controls in a FormView control

4.7k Views Asked by At

I'm using a FormView control (myFormView) with an EditItemTemplate which contains a number of child controls. When I use a standard ASP.Net DropDownList control (myDropList), I can obtain a reference to myDropList using the line below:

((DropDownList)myFormView.FindControl("myDropList"))

I can full access the properties of the myDropList and obtain the value currently selected. This is great.

However, I now need to use a 3rd party child control (FreeTextBox as found here http://www.freetextbox.com) in the FormView control. I've called the FreeTextBox control myFTB and I'm using a similar statement as above:

((FreeTextBox)myFormView.FindControl("myFTB"))

However, this returns null and thus I'm enable to retrieve property values for this.

Does anyone know why it is returning null? Is there some other way to retrieve the reference to the control?

TIA

2

There are 2 best solutions below

0
On BEST ANSWER

You will need to use recursion to find the control in the controls hierarchy.

Try using the following method:

FreeTextBox textBox = (FreeTextBox)FindControl(myFormView, "myFTB");

...

private Control FindControl(Control parent, string id)
{
    foreach (Control child in parent.Controls)
    {
        string childId = string.Empty;
        if (child.ID != null)
        {
            childId = child.ID;
        }

        if (childId.ToLower() == id.ToLower())
        {
            return child;
        }
        else
        {
            if (child.HasControls())
            {
                Control response = FindControl(child, id);
                if (response != null)
                    return response;
            }
        }
    }

    return null;
}
0
On

you can do like this to find controls in form view ....

NOte: The below code find the all text boxes inside the form view control

 protected void FormView1_DataBound(object sender, EventArgs e)
 {
        if (FormView1.CurrentMode == FormViewMode.Edit)
        {
            FindAllTextBoxes(FormView1);
        }
 }

 private void FindAllTextBoxes(Control parent)
 {
        foreach (Control c in parent.Controls)
        {
            if (c.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
            {
                TextBox tbox = c as TextBox;
                if (tbox != null)
                {
                    // textbox found ....you could send this textbox, by reference to another procedure that assigns the values comparing
                    //it by tbox.ID
                }
            }
            if (c.Controls.Count > 0)
            {
                FindAllTextBoxes(c);
            }
        }
  }

I hope it will helps you..