Foreach循环在Aspx页面中如何添加复选框和标签

本文关键字:添加 复选框 标签 何添加 循环 Aspx Foreach | 更新日期: 2023-09-27 17:58:03

Aspx页面中的Foreach循环如何从数据表中添加复选框和标签值。接收所有勾选的复选框值。

我在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>
<%  }   %>

Foreach循环在Aspx页面中如何添加复选框和标签

我认为您只是缺少了标签的:=<%应该是<%:。使用:对任何html进行编码,避免js注入。关于=: 的更多信息

<% 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>
<% } %>

您可以这样做:

 List<user> userList = new List<user>();
        foreach (user usr in userList)
        {
            PlaceHolder1.Controls.Add(new CheckBox()
                                          {
                                              ID = "cb_"+usr.UserId,
                                              Text = usr.Name,
                                              });    
        }

我认为向asp.net页面动态添加控件的最佳方式是onit页面事件。

你应该试试这样的东西。

    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); 
        }
    }