FindControl для Formview, который находится внутри пользовательского элемента управления

У меня есть Multiformview на моей странице aspx, например:

<data:MultiFormView ID="mFormView1" DataKeyNames="Id" runat="server" DataSourceID="DataSource">

            <EditItemTemplate>
                <ucl:myControl ID="myControl1" runat="server" />
            </EditItemTemplate>

And inside my user control 'mycontrol' I have adropdownlist like below:

<asp:FormView ID="FormView1" runat="server" OnItemCreated="FormView1_ItemCreated">
    <ItemTemplate>
        <table border="0" cellpadding="3" cellspacing="1">

            <tr>
                <td>
                    <asp:DropDownList ID="ddlType" runat="server" Width="154px" />
                </td>
            </tr>

Поэтому, когда я попытался получить доступ к этому раскрывающемуся списку внутри моего файла ascx.cs, он дает мне нулевую ссылку.

Я пробовал следующее:

    protected void FormView1_ItemCreated(Object sender, EventArgs e)
    {
           DropDownList ddlType= FormView1.FindControl("ddlType") as DropDownList;
    }

И

DropDownList ddlType= (DropDownList)FormView1.FindControl("ddlType");

И: Внутри Databound также. Ничего не работает.

РЕДАКТИРОВАТЬ:

Я не проверял, является ли Formview1.Row нулевым или нет. Вот решение:

 protected void FormView1_DataBound(object sender, EventArgs e)
    {
        DropDownList ddlType = null;
        if (FormView1.Row != null)
        {
            ddlType = (DropDownList)FormView1.Row.FindControl("ddlType");
        }
     }

person user1882705    schedule 03.04.2013    source источник


Ответы (2)


Вот метод расширения, который позволяет искать рекурсивно. Он расширяет ваши текущие элементы управления с помощью метода FindControlRecursive.

using System;
using System.Web;
using System.Web.UI;

public static class PageExtensionMethods
{
    public static Control FindControlRecursive(this Control ctrl, string controlID)
    {
        if (ctrl == null || ctrl.Controls == null)
            return null;

        if (String.Equals(ctrl.ID, controlID, StringComparison.OrdinalIgnoreCase))
        {
            // We found the control!
            return ctrl;
        }

        // Recurse through ctrl's Controls collections
        foreach (Control child in ctrl.Controls)
        {
            Control lookFor = FindControlRecursive(child, controlID);
            if (lookFor != null)
                return lookFor;
            // We found the control
        }
        // If we reach here, control was not found
        return null;
    }
}
person BabyGuru    schedule 03.04.2013

Я не проверял, является ли Formview1.Row нулевым или нет. Вот решение:

 protected void FormView1_DataBound(object sender, EventArgs e)
    {
        DropDownList ddlType = null;
        if (FormView1.Row != null)
        {
            ddlType = (DropDownList)FormView1.Row.FindControl("ddlType");
        }
     }
person user1882705    schedule 03.04.2013