为GridView添加复选框的方法

发布时间:2019-12-18编辑:脚本学堂
为GridView添加复选框的方法

GridView添加复选框的方法,详见代码。

1) .aspx:
 

复制代码 代码如下:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
            Caption="user" CaptionAlign="Top" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" DataKeyNames="username">
            <PagerSettings Mode="NextPrevious" Position="TopAndBottom" />
            <Columns>
                <asp:TemplateField HeaderText="select">
                    <EditItemTemplate>
                        <asp:checkbox ID="CheckBox1" runat="server" />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="username" HeaderText="username" />
            </Columns>
        </asp:GridView>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

2) .cs:(注意前提是你必须设置了GridView的DataKeyNames为主健)
 

复制代码 代码如下:
protected void Button1_Click(object sender, EventArgs e)
    {
        for(int i=0;i<GridView1.Rows.Count;i++)
        {
            CheckBox cb=(CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
            if (cb.checked)
            {
                string name = GridView1.DataKeys[GridView1.Rows[i].RowIndex].Value.ToString();
                //string name = GridView1.Rows[i].Cells[1].Text;
                Label1.Text+=name;
            }
        }
    }