2011-09-01 50 views
1

我有一个gridview有一个复选框列。该列的标题是复选框。在gridview中选择所有在回发问题上使用javascript

当它被选中时,所有的值都被检查并反之。

我使用javascript来做到这一点。

问题是如果我检查它并在页面上执行任何其他事件需要回发检查值消失。我不想让他们消失。

这里是我的代码:

<script type="text/javascript"> 

function checkAllBoxes() { 

     //get total number of rows in the gridview and do whatever 
     //you want with it..just grabbing it just cause 
     var totalChkBoxes = parseInt('<%= GridView1.Rows.Count %>'); 
     var gvControl = document.getElementById('<%= GridView1.ClientID %>'); 

     //this is the checkbox in the item template...this has to be the same name as the ID of it 
     var gvChkBoxControl = "Select_CheckBox"; 

     //this is the checkbox in the header template 
     var mainChkBox = document.getElementById("chkBoxAll"); 

     //get an array of input types in the gridview 
     var inputTypes = gvControl.getElementsByTagName("input"); 

     for (var i = 0; i < inputTypes.length; i++) { 
      //if the input type is a checkbox and the id of it is what we set above 
      //then check or uncheck according to the main checkbox in the header template    
      if (inputTypes[i].type == 'checkbox' && inputTypes[i].id.indexOf(gvChkBoxControl, 0) >= 0) 
       inputTypes[i].checked = mainChkBox.checked; 
     } 
    } 

    </script> 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"> 
<Columns> 
<asp:TemplateField> 
    <HeaderTemplate> 
    <input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()"/> 
    </HeaderTemplate> 
    <ItemTemplate> 
    <asp:CheckBox ID="Select_CheckBox" runat="server" /> 
    </ItemTemplate> 
</asp:TemplateField> 
<!-- The rest of your rows here --> 
</Columns> 
</asp:GridView> 

感谢您的帮助。

回答

2

使您的复选框成为使用视图状态的服务器端控件,方法是添加runat="server"。然后它将在邮寄期间保持其价值。

<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()" runat="server"/> 

并更改JavaScript以选择以chkBoxAll结尾的ID。我使用jQuery在下面的例子:

//this is the checkbox in the header template 
var mainChkBox = $('input[id$="chkBoxAll"]'); 

但是,如果你解决你的GridView行或使用分页,你可能会遇到不那么友好的行为。

+0

我得到这个......错误CS0103:名称'chkBoxAll'在当前上下文中不存在 – user175084

+1

我在一分钟前编辑它。你有'<%= chkBoxAll.ClientID%>'?我忘了在编辑之前添加'ClientID'。 –

+0

哦射..只是一分钟 – user175084