直接在 aspx 页上添加动态控件,而不是从后端代码添加动态控件
本文关键字:添加 动态控件 后端 代码 aspx | 更新日期: 2023-09-27 18:32:53
我希望复选框控件动态添加,在循环中生成的不同标签中的不同 id
<table border="1">
<thead>
<%string j = " Check"; %>
<%for (int i = 0; i < 10;i++ )
{%>
<th style="padding:2px; width:500px;">Table Head<br /><br />
<%
CheckBox chk = new CheckBox();
chk.ID = i + j;
chk.Text = "I am " + i + j;
%>
//I want this checkbox to be added dynamically here with different id's in different th tags generating in a loop
<asp:CheckBox runat="server" ID="<%=i+j%>"/>
</th>
<%} %>
</thead>
</table>
执行此操作
的方法是为自己创建一个包含所需所有参数的服务器控件,在 OnInit 中创建控件,在 RenderControl 中渲染 html,并从公共 props 访问控件,如下所示:
public class DynamicCbs : Control
{
public int CtrlsCount { get; set; }
public List<CheckBox> lstCheckBoxs;
/// decleration of controls must be in the OnInit since the next stage of the page life cycle is to connect whatever came back from the client to the server
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
lstCheckBoxs = new List<CheckBox>();
for (int i = 0; i < CtrlsCount; i++)
{
string id = "DynamicCbs" + i;
CheckBox cbx = new CheckBox()
{
ID = id,
Text = "i am " + id
};
lstCheckBoxs.Add(cbx);
//add controls to control tree
this.Controls.Add(cbx);
}
}
/// here you must build ur html
public override void RenderControl(HtmlTextWriter writer)
{
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Thead);
foreach (var cbx in lstCheckBoxs)
{
writer.RenderBeginTag(HtmlTextWriterTag.Th);
cbx.RenderControl(writer);
writer.RenderEndTag();
}
writer.RenderEndTag();//thead
writer.RenderEndTag();//table
}
}
完整示例
好的,
我找到了解决方案。我使用 asp:Table 控件来解决这个问题 我的 aspx 页面代码是:
<asp:Table ID="ObjectwiseTable2" runat="server"
CssClass="AccessTable" BorderColor="Black" width="100%">
</asp:Table>
我在表格中添加内容和动态内容的.cs页面代码是:
TableHeaderRow thead = new TableHeaderRow();
TableHeaderCell th = new TableHeaderCell();
th.Controls.Add(new LiteralControl("Object Wise Detail(s)"));
th.RowSpan = 2;
thead.Cells.Add(th);
int totalUsers = accesswiseDt.Rows.Count;
for (int User = 0; User < totalUsers; User++)
{
TableHeaderCell th2 = new TableHeaderCell();
th2.Controls.Add(new LiteralControl(accesswiseDt.Rows[User]["users"].ToString()));
IsReviewPending = view_access.IsWaitingForViewAccess(ApplicationTree.SelectedNode.Value, Session["empCode"].ToString(), accesswiseDt.Rows[User]["empcode"].ToString());
if (IsReviewPending)
{
th2.Controls.Add(new LiteralControl("<br />"));
CanReviewAccess = true;
//Code for Adding Dynamic control in specific cell of the table
CheckBox chk = new CheckBox();
chk.ID = ApplicationTree.SelectedNode.Value + "_" + accesswiseDt.Rows[User]["empcode"].ToString();
chk.Text = "Access Reviewed";
th2.Controls.Add(chk);
}
thead.Cells.Add(th2);
}