在GridView里加CheckBox是比较常见的情景,下面的代码是最简单的获取选择那些checked的行的信息,代码直接复制,配置好连接字符串和数据库表后可用.

.aspx:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp; &nbsp;
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                    SortExpression="ID" />
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>"
            SelectCommand="SELECT [ID], [Name] FROM [test1]"></asp:SqlDataSource>
        &nbsp;
    </div>
    </form>
</body>


.cs:

    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvr in GridView1.Rows)
        {
            CheckBox cb = (CheckBox)gr.FindControl("CheckBox1");
            if (cb.Checked)
            {
                Response.Write(gr.Cells[0].Text);
                Response.Write("</br>");
            }
        }
    }

如果想加上全选功能,在.aspx加上以下代码:
<HeaderTemplate>
                        <asp:CheckBox ID="CheckBox2" runat="server" onclick="javascript:SelectAll(this);" style="position: relative" />
                    </HeaderTemplate>
      <script language="javascript">
       function SelectAll(tempControl)
       {
           //将除头模板中的其它所有的CheckBox取反

            var theBox=tempControl;
             xState=theBox.checked;   

            elem=theBox.form.elements;
            for(i=0;i<elem.length;i++)
            if(elem[i].type=="checkbox" && elem[i].id!=theBox.id)
             {
                  if(elem[i].checked!=xState)
                        elem[i].click();
            }
  } 
</script>

以后会补上分页的情况.

posted on 2006-10-24 10:51  有些伤感  阅读(881)  评论(0编辑  收藏  举报