筆記 - C# 在Asp.net 的GridView 中使用JavaScript加入全選按鈕的方法.

筆記 -  C# 在Asp.net  的GridView 中使用JavaScript加入全選按鈕的方法.

//在Web Form GridView 部份

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"           
onrowdatabound="GridView1_RowDataBound" >           
            
            <Columns>
                <asp:TemplateField>
                
                <HeaderTemplate>
                <asp:CheckBox ID="allchk" runat="server" Text="All" />  </HeaderTemplate>

                <ItemTemplate>
                
                <asp:CheckBox ID="selectchk"  runat="server" />
               
                </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="TR. ID">
                
                <ItemTemplate>
                <asp:Label ID="namelbl" 
                    runat="server" Text='<%#Eval(
                    "name") %>'></asp:Label>
                </ItemTemplate>
                 </asp:TemplateField>
                
            </Columns>
        </asp:GridView>

//在Code Behine 部份
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
       {

          //header select all function
           if (e.Row.RowType == DataControlRowType.Header)
           {
               ((CheckBox)e.Row.FindControl("allchk")).Attributes.Add("onclick",
                   "javascript:SelectAll('" +
                   ((CheckBox)e.Row.FindControl("allchk")).ClientID + "')");
           }

           }

//在Javescript 部份

<script type="text/javascript">
        function SelectAll(id)
        {
            //get reference of GridView control
            var grid = document.getElementById("<%= GridView1.ClientID %>");
            //variable to contain the cell of the grid
            var cell;
            
            if (grid.rows.length > 0)
            {
                //loop starts from 1. rows[0] points to the header.
                for (i=1; i<grid.rows.length; i++)
                {
                    //get the reference of first column
                    cell = grid.rows[i].cells[0];
                    
                    //loop according to the number of childNodes in the cell
                    for (j=0; j<cell.childNodes.length; j++)
                    {           
                        //if childNode type is CheckBox                 
                        if (cell.childNodes[j].type =="checkbox")
                        {
                        //assign the status of the Select All checkbox to the cell 
                        //checkbox within the grid
                            cell.childNodes[j].checked = document.getElementById(id).checked;
                        }
                    }
                }
            }
        }
    </script>