使用 Javascript 在 GridView 中选中/取消选中复选框
使用 javascript 在 GridView 内部选中/取消选中复选框控件,无需回发。
引言
使用 javascript 在 GridView 内部选中/取消选中复选框控件,无需回发。本文将介绍如何实现此任务。
在“使用代码”标题下提供了部分示例代码,完整的代码可在项目下载中找到。
背景
(论坛上充斥着关于如何使用 javascript 在 GridView 内部选中/取消选中复选框控件,无需回发的问题。)
操作指南
本文中使用了一个 GridView 控件。在 GridView 控件内部有 3 个字段。一个模板字段和两个绑定字段,用于显示一些示例数据。
在 TemplateField 内部,在 HeaderTemplate(ID 为 cbSelectAll,文本为“全选”)、ItemTemplate 和 AlternatingItemTemplate 中放置了一个 CheckBox 控件。
使用代码
实现此任务所需的代码。
执行“全选”操作所需的 Javascript 如下
    <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>		添加 cbSelectAll 复选框属性所需的代码如下
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //Binding GridView with the datasource //FillDataTable is a method that will return a DataTable //filled with some rows (code available in download) this.GridView1.DataSource = FillDataTable(); this.GridView1.DataBind(); } } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { //Find the checkbox control in header and add an attribute ((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')"); } }
单击“全选”复选框之前
单击“全选”复选框之后




