簡體   English   中英

用戶控件內部的Formview的FindControl

[英]FindControl of a Formview which is inside an user control

我的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文件中的該dropdownlist時,它給了我null引用錯誤。

我嘗試了以下操作:

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

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

AND:也在Databound內部。 什么都沒用。

編輯:

我沒有檢查Formview1.Row是否為null。 解決方法如下:

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

這是一個擴展方法,它允許搜索遞歸。 它使用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.Row是否為null。 解決方法如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM