javascript Aspx页面中的Foreach循环如何添加复选框和标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14729731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Foreach loop in Aspx page how to add checkbox and label
提问by user1881251
Foreach loop in Aspx page how to add checkbox and label values from datatable . Recieve all ticked checkbox value.
Aspx 页面中的 Foreach 循环如何从数据表中添加复选框和标签值。接收所有勾选的复选框值。
I have written this code in aspx page not in aspx.cs .
我已经在 aspx 页面中而不是在 aspx.cs 中编写了此代码。
<% foreach (Employee myEmp in _empList) {
empName = myEmp.ToString(); %>
<div class="abc">
<div class="pqr">
<asp:Label Text="<% empName %>" runat="server" ID="lblEmpName"></asp:Label></label>
</div>
<div class="xyz">
<asp:CheckBox ID="chkBox" Checked="false" runat="server" />
</div>
</div>
<% } %>
回答by cagin
You can do something like this:
你可以这样做:
List<user> userList = new List<user>();
foreach (user usr in userList)
{
PlaceHolder1.Controls.Add(new CheckBox()
{
ID = "cb_"+usr.UserId,
Text = usr.Name,
});
}
回答by Muhammad Noman
I think the best way to add controls dynamically to asp.net page is oninit page-event.
我认为将控件动态添加到 asp.net 页面的最佳方法是 oninit 页面事件。
you should try something like this.
你应该尝试这样的事情。
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
/*LinkButton lb = new LinkButton();
lb.ID = "lbAddFilter";
pnlFilter.Controls.Add(lb);
lb.Text = "Add Filter";
lb.Click += new EventHandler(lbAddFilter_Click);*/
// regenerate dynamically created controls
foreach ( var employee in employeeList)
{
Label myLabel = new Label();
// Set the label's Text and ID properties.
myLabel.Text = "Label" + employee.Name.ToString();
myLabel.ID = "Label" + employee.ID.ToString();
CheckBox chkbx = new CheckBox();
chkbx.ID = "CheckBox" + employee.ID.ToString();
chkbx.Text = "Label" + employee.Name.ToString();
MyPanel.Controls.Add(myLabel);
MyPanel.Controls.Add(chkbx);
}
}
回答by w00ngy
I think you're just missing the :
or =
for the label. <%
should be <%:
. Use :
to encode any html and avoid js injection. More infoon =
vs :
我认为您只是缺少:
或缺少=
标签。<%
应该是<%:
。使用:
以编码任何HTML和JS避免注射。更多信息关于=
VS:
<% foreach (Employee myEmp in _empList) {
empName = myEmp.ToString(); %>
<div class="abc">
<div class="pqr">
<asp:Label Text="<%: empName %>" runat="server" ID="lblEmpName"></asp:Label>
</div>
<div class="xyz">
<asp:CheckBox ID="chkBox" Checked="false" runat="server" />
</div>
</div>
<% } %>