【问题标题】:FindControl of a Formview which is inside an user control用户控件内的 Formview 的 FindControl
【发布时间】:2013-04-03 14:34:57
【问题描述】:

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

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

所以当我尝试访问我的 ascx.cs 文件中的这个下拉列表时,它给了我空引用错误。

我尝试了以下操作:

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

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

AND:也在数据绑定内部。什么都没有。

编辑:

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

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

【问题讨论】:

    标签: c# asp.net formview


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2010-12-08
        • 2013-09-22
        • 2018-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-17
        • 2014-09-17
        相关资源
        最近更新 更多