自动生成的复选框 - 检查是否已选中C#

时间:2014-04-16 14:05:39

标签: c#

我需要获取仅选中的复选框的值和ID。

的Index.aspx

<asp:Button ID="Button1" runat="server" Text="Download Files" OnClick="LoadFiles" />
<asp:Literal runat="server" ID="SubCategory" />

背后的代码

自动生成的复选框:

StringBuilder sb = new StringBuilder("");      
SqlDataReader dr = null;
dr = cmd.ExecuteReader();

while (dr.Read())
{
    sb.Append("<input runat=\"server\" type=\"checkbox\" value=\"" + dr["Attachment_Name"].ToString() + "\" name=\"chk_" + dr["Attachment_ID"].ToString() + "\">" + dr["Attachment_Name"].ToString() + "</input>&nbsp;&nbsp;");
}
dr.NextResult();

SubCategory.Text = sb.ToString();

我试过这个但是只有当它是CheckboxList时才有效:(这段代码来自我的另一个项目)

string values = "";

foreach (ListItem objItem in chkTopics.Items)
{
    if (objItem.Selected)
    {
        values += objItem.Value + ":";
    }
}

有点难过这个。

1 个答案:

答案 0 :(得分:0)

我已根据您的要求创建了一个示例页面。我希望它能为您提供帮助 标记:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SOA.aspx.cs" Inherits="SOA" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div id="checkboxesHolder" runat="server">
        </div>
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

服务器端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class SOA : System.Web.UI.Page {
    private List<String> GetNames() {
        return Enumerable.Range(1, 10).Select(x => string.Format("Checkbox_{0}", x)).ToList();
    }
    protected void Page_Load(object sender, EventArgs e) {
        CreateCheckboxes();
        if(IsPostBack)
            ReadCheckboxes();
    }

    private void ReadCheckboxes() {
        var selectedName = GetNames().Where(x => Request.Form[x] == "checked");
    }

    private void CreateCheckboxes() {
        foreach(var name in GetNames()) {
            var checkbox = new HtmlInputCheckBox();
            checkbox.ID = name;
            checkbox.Value = "checked";
            checkbox.Name = name;
            checkboxesHolder.Controls.Add(checkbox);
            checkboxesHolder.Controls.Add(new LiteralControl(name));
        }
    }
}
相关问题