ASP.NET2.0中GridView加入CheckBox實現全選!

來源:互聯網
上載者:User

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

<!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 language="javascript" type="text/javascript">
    function selectAll(obj)
    {
        var theTable  = obj.parentElement.parentElement.parentElement;
        var i;
        var j = obj.parentElement.cellIndex;
       
        for(i=0;i<theTable.rows.length;i++)
        {
            var objCheckBox = theTable.rows[i].cells[j].firstChild;
            if(objCheckBox.checked!=null)objCheckBox.checked = obj.checked;
        }
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            DataKeyNames="id" DataSourceID="AccessDataSource1" AllowSorting="True" OnDataBinding="GridView1_DataBinding" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" Checked="True" Text='<%#DataBinder.Eval(Container.DataItem,"id") %>' />
                    </ItemTemplate>
                    <HeaderTemplate>
                        &nbsp;<input id="CheckAll" type="checkbox" onclick="selectAll(this);" />本頁全選
                    </HeaderTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
                    SortExpression="id" />
                <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
                <asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
                <asp:BoundField DataField="deptid" HeaderText="deptid" SortExpression="deptid" />
            </Columns>
        </asp:GridView>
        &nbsp;
     
        <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/test.mdb"
            SelectCommand="SELECT [id], [name], [sex], [deptid] FROM [employees]"></asp:AccessDataSource>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="ShowAllSelectedItem" />
        <asp:TextBox ID="TextBox1" runat="server" Width="200px" ReadOnly="True"></asp:TextBox></div>
    </form>
</body>
</html>

************************************
************************************
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class GridSamples_GridView_CheckBoxColumn : System.Web.UI.Page
{
    /// <summary>
    /// 擷取或設定選中項的集合
    /// </summary>
    protected ArrayList SelectedItems
    {
        get
        {
            return (ViewState["mySelectedItems"] != null) ? (ArrayList)ViewState["mySelectedItems"] : null;
        }
        set
        {
            ViewState["mySelectedItems"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
       
    }

    protected void GridView1_DataBinding(object sender, EventArgs e)
    {
        //在每一次重新綁定之前,需要調用CollectSelected方法從當前頁收集選中項的情況
        CollectSelected();
    }

   
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //這裡的處理是為了回顯之前選中的情況
        if (e.Row.RowIndex > -1 && this.SelectedItems!=null)
        {
            DataRowView row = e.Row.DataItem as DataRowView;
            CheckBox cb = e.Row.FindControl("CheckBox1") as CheckBox;
            if(this.SelectedItems.Contains(row["id"].ToString()))
                cb.Checked = true;
            else
                cb.Checked = false;
        }
    }
    /// <summary>
    /// 從當前頁收集選中項的情況
    /// </summary>
    protected void CollectSelected()
    {
        ArrayList selectedItems = null;
        if (this.SelectedItems == null)
            selectedItems = new ArrayList();
        else
            selectedItems = this.SelectedItems;

        for (int i = 0; i < this.GridView1.Rows.Count; i++)
        {
            string id = this.GridView1.Rows[i].Cells[1].Text;
            CheckBox cb = this.GridView1.Rows[i].FindControl("CheckBox1") as CheckBox;
            if (selectedItems.Contains(id) && !cb.Checked)
                selectedItems.Remove(id);
            if (!selectedItems.Contains(id) && cb.Checked)
                selectedItems.Add(id);
        }
        this.SelectedItems = selectedItems;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        //最後,需要對選中項進行操作之前,不能忘了還要最後一次收集當前頁的選中情況
        CollectSelected();

        this.TextBox1.Text = string.Empty;
        foreach (object tmp in this.SelectedItems)
            this.TextBox1.Text += tmp.ToString() + ",";
    }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.