从代码背后调用动态创建的控件

时间:2016-03-09 18:19:35

标签: c# html asp.net innerhtml

我正在使用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);
                }

1 个答案:

答案 0 :(得分:0)

经过一番研究,我找到了一个名为Repeater的ASP.NET控件。这在创建动态ul时非常有用。

这是我用来动态加载数据库中的值的代码。

postHandler.downloadItems()