Check Uncheck all CheckBoxes in an ASP.NET GridView kept in an Update Panel using jQuery

In one of my previous posts, I had shown how to Check Uncheck all CheckBoxes in an ASP.NET GridView using jQuery

Users mailed back telling me that the example did not work in an UpdatePanel. I suspect the error they got was this:

“Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled”

The reason why this error occurs has been given very clearly over here

Here’s how to solve it:

1. Wrap the GridView and the Button in an Update Panel

2. Add a Literal control to the Page

<asp:Literal ID="lblResults" runat="server" Text=""></asp:Literal>

3. Instead of using Response.Write(), write the results to this Literal control

C#

protected void btnRetrieveCheck_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chkSel");
if (cb != null && cb.Checked)
{
lblResults.Text += "Employee Id: " +
GridView1.DataKeys[row.RowIndex].Value
+ " Name: " + row.Cells[2].Text + "<br/>";
}
}
}

VB.NET

Protected Sub btnRetrieveCheck_Click(ByVal sender As Object, _
ByVal e As EventArgs)
For Each row As GridViewRow In GridView1.Rows
Dim cb As CheckBox = CType(row.FindControl("chkSel"), CheckBox)
If cb IsNot Nothing AndAlso cb.Checked Then
lblResults.Text &= "Employee Id: " & _
GridView1.DataKeys(row.RowIndex).Value & " Name: " & _
row.Cells(2).Text & "<br/>"
End If
Next
row
End Sub





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: