在用户控件内部的Formview的FindControl

本文关键字:Formview FindControl 内部 用户 控件 | 更新日期: 2023-09-27 18:07:10

我有一个Multiformview在我的aspx页面,像:

<data:MultiFormView ID="mFormView1" DataKeyNames="Id" runat="server" DataSourceID="DataSource">
            <EditItemTemplate>
                <ucl:myControl ID="myControl1" runat="server" />
            </EditItemTemplate>

在我的用户控件'mycontrol'中,我有如下的下拉列表:

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

所以当我试图访问这个下拉列表在我的asx .cs文件它给我null引用错误。

我试过如下:

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

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

AND: Inside Databound also。

编辑:

我没有检查Formview1。行是否为空。解决方案如下:

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

在用户控件内部的Formview的FindControl

这是一个扩展方法,它允许递归搜索。它使用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;
    }
}

我没有检查Formview1。行是否为空。解决方案如下:

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