在用户控件内的Formview的FindControl

时间:2013-04-03 14:34:57

标签: c# asp.net formview

我的aspx页面中有一个Multiformview,如:

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

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

在我的用户控件'mycontrol'中,我有如下的adropdownlist:

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

AND

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

AND:内部数据绑定也。没有什么工作。

编辑:

我没有检查Formview1.Row是否为null。这是解决方案:

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

2 个答案:

答案 0 :(得分:2)

这是一个扩展方法,允许搜索递归。它使用FindControl Recursive方法扩展当前控件。

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

答案 1 :(得分:2)

我没有检查Formview1.Row是否为null。这是解决方案:

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