簡體   English   中英

從背后的代碼調用動態創建的控件

[英]Calling Dynamically Created Control From Code Behind

我正在使用HtmlGenericControl方法動態創建一個控件,然后嘗試在我的代碼中向下調用該控件幾行。 顯然,由於尚未真正創建此控件,因此代碼會引發構建錯誤。 是否有任何解決方法? 這是我正在使用的代碼:

foreach(string t in equipmentTypes)
{
    HtmlGenericControl li = new HtmlGenericControl("li");//Create html control <li>
    //Create the correct <li> for the equipment type. Using the naming convention tableAbreviation_recordName eg: et_ATV.
    li.InnerHtml = "<div id='et_" + t +"' >" + t + "<label><input type='checkbox'></label></div><ul id='make' runat='server'>";
    equipmentType.Controls.Add(li);
}

makes = Statements.GetMake();

foreach(string t in makes)
{
    HtmlGenericControl li = new HtmlGenericControl("li");//Create html control <li>
    //Create the correct <li> for the equipment type. Using the naming convention tableAbreviation_recordName eg: et_ATV.
    li.InnerHtml = "<div id='mk_" + t + "' >" + t + "<label><input type='checkbox'></label></div>";
    make.Controls.Add(li);
}

因此,我正在創建id ='make'的<ul> 我想在下一個foreach循環中將此<ul>稱為附加html。 我將如何處理?

經過一些進一步的研究,我嘗試使用Page.FindControl查找控件,但是按照代碼運行/頁面創建的順序,該對象未設置為對象的實例。 如此看來,頁面渲染后,我可能需要調用控件?

我用來嘗試找到該控件的代碼與上一個foreach循環相同,但最后一行除外。

foreach(string t in makes)
                {
                    HtmlGenericControl li = new HtmlGenericControl("li");//Create html control <li>
                    //Create the correct <li> for the equipment type. Using the naming convention tableAbreviation_recordName eg: et_ATV.
                    li.InnerHtml = "<div id='mk_" + t + "' >" + t + "<label><input type='checkbox'></label></div>";
                    Page.FindControl("ATV_make").Controls.Add(li);
                }

經過研究,我找到了一個名為Repeater的ASP.NET控件。 創建動態ul時,這非常有用。

這是我用來從數據庫動態加載值的代碼。

<asp:Repeater ID="Repeater1" runat="server">
        <HeaderTemplate><ul></HeaderTemplate>
        <ItemTemplate><li><div id="et_"><%# Eval("EquipmentTypeName") %><label><input type="checkbox"></label></div><ul id="_make" runat="server">
            <asp:Repeater ID="Repeater2" runat="server" DataSourceID="SQL_Make">
                <ItemTemplate>
                    <li><div id="mk_"><%# Eval("MakeName") %><label><input type="checkbox"></label></div><ul id="_year" runat="server"></ul></li>
                </ItemTemplate>
            </asp:Repeater>
        </ul></li></ItemTemplate>
        <FooterTemplate></ul></FooterTemplate>
    </asp:Repeater>

暫無
暫無

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

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