方法一

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
    <script runat="server">  
  protected void Button1_Click(object sender, EventArgs e)
  {
    FindBox(this.Controls);
  }

  private void FindBox(ControlCollection cc)
  {

      string CheckString = "";
      foreach (Control c in cc)
      {
          if (c.HasControls())
          {
              FindBox(c.Controls);
          }
          if (c is CheckBox)
          {
              CheckBox cb = c as CheckBox;
              if (cb.Checked)
              {
                  CheckString += cb.Text.Replace("CheckBox", "").Trim() + ",";
              }
          }
      }
      Response.Write(""+CheckString+"");

  }
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:CheckBox ID="CheckBox7" runat="server" name="xxxxx" Text=" xxxxx" />
  <asp:CheckBox ID="CheckBox1" runat="server" name="Admin_Power" Text=" 投票1" />
  <asp:CheckBox ID="CheckBox2" runat="server" name="Admin_Power" Text=" 投票2" />
  <asp:CheckBox ID="CheckBox3" runat="server" name="Admin_Power" Text=" 投票3" />
  <asp:CheckBox ID="CheckBox4" runat="server" name="Admin_Power" Text=" 投票4" />
  <asp:CheckBox ID="CheckBox5" runat="server" name="Admin_Power" Text=" 投票5" />
  <asp:CheckBox ID="CheckBox6" runat="server" name="Admin_Power" Text=" 投票6" />
  <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="得到" />

    </div>
    </form>
</body>
</html>

 方法二

protected void Button1_Click(object sender, EventArgs e)
    {
        string CheckString = "";
        foreach (Control ct in form1.Controls)
        {
            if (ct.GetType().ToString().Equals("System.Web.UI.WebControls.CheckBox"))
            {
                CheckBox cb = (CheckBox)ct;
                if (cb.Checked)
                {
                    CheckString += cb.Text.Replace("CheckBox", "").Trim() + ",";
                }
            }

        }

        this.Label3.Text = CheckString;
    }

你的checkbox在form里,你只能在form中循环遍历。

所以你必须先得到form这个对象。

如果是母版页,你可以先这样来得到form

HtmlForm f = this.FindControl("form的id") as HtmlForm;
或者也许是this.Master.FindControl("form的id") as HtmlForm;

遍历页面上的CheckBoxList:

 string CheckString = "";
      foreach (Control c in this.form1.Controls) //母版页:foreach (Control c in this.Page.Master.FindControl("ContentPlaceHolder1").Controls
)
      {
          if (c is CheckBoxList)
          {
              foreach (ListItem item in (c as CheckBoxList).Items)
              {
                  if (item.Selected == true)
                  {
                      CheckString += item.Value + ",";

                  }
              }
          }
      }

 

 posted on 2012-07-14 15:32  纳米程序员  阅读(3689)  评论(0编辑  收藏  举报