2013年9月4日 星期三

實作GridView裡的checkbox全選


常常會碰到需要對GridView裡的checkbox作全選的動作,用jQuery來做的話,其實還滿方便的

在此記錄一下


[default.aspx]

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Lab_CheckAllInGridView._default" %>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>CheckBox 全選</title>
    <script type="text/javascript" src="Scripts/jquery-2.0.2.min.js"></script>
    <script type="text/javascript">
        //  選擇 GridView 全部的 checkbox
        //  傳入控制checkbox全選的checkbox物件
        function checkAll(header) {
            $('#<%= gvData.ClientID %> input[type=checkbox]').prop("checked", header.checked);
           
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="選取">
                    <HeaderTemplate>
                        <asp:CheckBox ID="cbHeader" runat="server" onclick="checkAll(this);" />
                        選取
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="cbDel" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Name" HeaderText="姓名" />
                <asp:BoundField DataField="Age" HeaderText="年齡" />
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

[default.aspx.cs]


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Lab_CheckAllInGridView
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    public partial class _default : System.Web.UI.Page
    {
        private List<Person> GetData()
        {
            List<Person> personList = new List<Person>();
            personList.Add(new Person { Name = "Lily", Age = 18 });
            personList.Add(new Person { Name = "Joseph", Age = 20 });
            personList.Add(new Person { Name = "Ella", Age = 22 });
            personList.Add(new Person { Name = "Tom", Age = 45 });
            personList.Add(new Person { Name = "John", Age = 33 });
            personList.Add(new Person { Name = "Bill", Age = 10 });
            personList.Add(new Person { Name = "Dio", Age = 35 });
            return personList;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
           
            this.gvData.DataSource = this.GetData();
            this.gvData.DataBind();
        }
    }
}

沒有留言:

張貼留言