GridView中的CheckBox(bug已经修复)

1.html

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_CheckBox.aspx.cs"
    Inherits
="GridView_GridView_CheckBox" MaintainScrollPositionOnPostback="true" 
%>

<!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>GridView中的CheckBox</title>
    
<%--    <script language="javascript" type="text/javascript">
     
function CheckBox_SeleltAll(aa) 
     {
          
//方法1.
          
//全选/全取消                   
            var gridview 
= document.getElementById("<%=GridView1.ClientID %>");
            
for(var i = 1; i < gridview.rows.length; i ++)
            {
                gridview.rows[i].cells[
0].getElementsByTagName("input")[0].checked = aa.checked;
            }

          
//方法2
          
//全选/全取消
          var gvObj;
          
for(var i = 1; i < form1.length; i ++)
          {
            
if(form1.elements[i].type == "checkbox")
            {
                gvObj 
= form1.elements[i];
                gvObj.checked 
= aa.checked;
            }
          }
     }
    
</script>--
%>
</head>
<body onload="AttachListener()">
    
<form id="form1" runat="server">
        
<div>
            
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Width="100%">
                
<Columns>
                    
<asp:TemplateField>
                        
<HeaderTemplate>
                            
<input type="checkbox" id="chkAll" name="chkAll" onclick="Check(this)" />
                        
</HeaderTemplate>
                        
<ItemTemplate>
                            
<%--<input type="checkbox" id="chkSelect" name="chkSelect" />--%>
                            
<asp:CheckBox ID="chkSelect" runat="server" />
                        
</ItemTemplate>
                    
</asp:TemplateField>
                    
<asp:BoundField DataField="au_id" HeaderText="au_id" />
                    
<asp:BoundField DataField="au_lname" HeaderText="au_lname" />
                    
<asp:BoundField DataField="au_fname" HeaderText="au_fname" />
                    
<asp:BoundField DataField="phone" HeaderText="phone" />
                    
<asp:BoundField DataField="address" HeaderText="address" />
                
</Columns>
            
</asp:GridView>
            
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="js_c#_checkbox" />&nbsp;
            
<br />
            
<asp:Literal ID="Ret2" runat="server"></asp:Literal>
        
</div>
    
</form>
</body>
</html>

<script language="javascript" type="text/javascript">
var counter = 0;
var pattern = '^GridView1';

// Get the checkboxes inside the Gridview which is part of the template column
function GetChildCheckBoxCount() 
{    
    
var checkBoxCount = 0;  
    
var elements = document.getElementsByTagName("INPUT"); 
    
    
for(i=0; i<elements.length;i++
    
{
        
if(IsCheckBox(elements[i]) &&  IsMatch(elements[i].id)) checkBoxCount++
    }

    
   
return parseInt(checkBoxCount); 
}


// A function that checks if the checkboxes are the one inside the GridView 
function IsMatch(id) 
{
    
var regularExpresssion = new RegExp(pattern); 
    
    
if(id.match(regularExpresssion)) return true
    
else return false
}


function IsCheckBox(chk) 
{
    
if(chk.type == 'checkbox') return true
    
else return false;
}


function AttachListener()
{
    
var elements =  document.getElementsByTagName("INPUT");
    
    
for(i=0; i< elements.length; i++
    
{       
        
if( IsCheckBox(elements[i]) &&  IsMatch(elements[i].id)) 
        
{
            AddEvent(elements[i],'click',CheckChild); 
        }

    }
    
}


function CheckChild(e) 
{
    
var evt = e || window.event; 
    
var obj = evt.target || evt.srcElement 
  
    
if(obj.checked)
    
{
        
if(counter < GetChildCheckBoxCount()) 
            
{ counter++; }        
    }
    
            
    
else 
    
{
       
if(counter > 0{ counter--; }    
    }
 
       
    
if(counter == GetChildCheckBoxCount()) 
    
{ document.getElementById("chkAll").checked = true; } 
    
else if(counter < GetChildCheckBoxCount()) { document.getElementById("chkAll").checked = false; }    
  
}


function AddEvent(obj, evType, fn) 
{
    
if (obj.addEventListener)
    
{
    obj.addEventListener(evType, fn, 
true);
    
return true;
    }

 
 
else if (obj.attachEvent)
 
{
    
var r = obj.attachEvent("on"+evType, fn);
    
return r;
 }

  
else
   
{
    
return false;
   }
    
}


function Check(parentChk) 
{
    
var elements =  document.getElementsByTagName("INPUT"); 
    
    
for(i=0; i<elements.length;i++
    
{
        
if(parentChk.checked == true
        
{  
            
if( IsCheckBox(elements[i]) &&  IsMatch(elements[i].id)) 
            
{
            elements[i].checked 
= true
            }
         
        }

        
else 
        
{
            elements[i].checked 
= false
            
// reset the counter 
            counter = 0
        }
       
    }

    
    
if(parentChk.checked == true
    
{
        counter 
= GetChildCheckBoxCount(); 
    }
     
}

</script>
2.cs
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 GridView_GridView_CheckBox : System.Web.UI.Page
{
    Practice.DAL.authors authorsbll 
= new Practice.DAL.authors();

    
protected void Page_Load(object sender, EventArgs e)
    
{
        
if (!IsPostBack)
        
{
            DataBindGridView();
        }

    }


    
/// <summary>
    
/// 功    能:绑定GridView
    
/// 作  者:PUKE
    
/// 完成时间:2007-05-18
    
/// 版  权:pukesys@tom.com
    
/// </summary>

    private void DataBindGridView()
    
{
        
string connectionString = "Server=localhost;Database=pubs;Trusted_Connection=true";
        System.Data.SqlClient.SqlConnection myConnection 
= new System.Data.SqlClient.SqlConnection(connectionString);
        System.Data.SqlClient.SqlDataAdapter da 
= new System.Data.SqlClient.SqlDataAdapter("select * from authors", myConnection);

        DataSet ds 
= new DataSet();
        da.Fill(ds);

        GridView1.DataSource 
= ds;
        GridView1.DataBind();
    }


    
/// <summary>
    
/// 功    能:提取选中项的id值
    
/// 作  者:PUKE
    
/// 完成时间:2007-05-18
    
/// 版  权:pukesys@tom.com
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>

    protected void Button2_Click(object sender, EventArgs e)
    
{
        Ret2.Text 
= "";
        
for (int i = 0; i < this.GridView1.Rows.Count; i++)
        
{
            GridViewRow gvr 
= this.GridView1.Rows[i];
            CheckBox ch 
= (CheckBox)gvr.FindControl("chkSelect");
            
if (ch.Checked)
            
{
                Ret2.Text 
+= "<li>GridView1 您选择的是(键值):" + GridView1.Rows[gvr.DataItemIndex].Cells[1].Text.ToString();
            }

        }

    }

    
}

原文地址:https://www.cnblogs.com/puke/p/768715.html