简单的GridView+CheckBox应用

在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" οnclick="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>

以后会补上分页的情况.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值