简体   繁体   中英

FindControl of a Formview which is inside an user control

I have a Multiformview inside my aspx page like:

<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>

So when i tried to access this dropdownlist inside my ascx.cs file it is giving me null reference error.

I tried following:

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

AND

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

AND: Inside Databound also. Nothing is working.

EDIT:

I Was not checking that Formview1.Row is null or not. Here is the solution:

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

Here's an extension method, which allows to search recursive. It extends your current constrols with the method 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;
    }
}

I Was not checking that Formview1.Row is null or not. Here is the solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM