开发者

SelectAll in gridview using javascript on postback issue

i have a gridview which has a checkbox column. 开发者_如何学CThe header is of this column is a checkbox.

When it is checked all the values get checked and vice-verse.

I do this using javascript.

The problem is if i check it and perform any other event on the page which requires a postback the checked values disappear. I dont want them to disappear.

here is my code:

 <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>

Thanks for the help.


Make your checkbox a server-side control that uses the view state by adding runat="server". It will then maintain its value across post backs.

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

And change your JavaScript to select the id that ends in chkBoxAll. I use jQuery in the example below:

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

However, if you sort your gridview rows or use paging, you will likely come across less friendly behavior.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜