Checking/unchecking all checkboxes in the one column of the gridview

  • Thread starter Thread starter schapopa
  • Start date Start date
S

schapopa

Hi,
I have gridview that contains many columns with checkboxes.
I added one more row below header that contains link buttons and I would
like to be able to check and uncheck all checkboxes in one column by
clicking on link button.
I saw some javascript solutions that do that but in case there is one
column with checkboxes. I am strugling with making that work for just
one column.
Does anyone has solution or link on how to make it work.
Thank you
Arek
 
Does anyone has solution or link on how to make it work.

There are essentially two ways of doing this:

1) Create individual client-side JavaScript arrays of the various sets of
checkbox IDs as the page loads. Each array contains the checkbox IDs for a
single column. Then include an extra argument in the client-side JavaScript
function which checks / unchecks the checkboxes so that it knows which array
to iterate through. This is described here:
http://www.4guysfromrolla.com/articles/052406-1.aspx

2) Use "intelligent" naming for the checkboxes and link buttons so that the
client-side JavaScript can tell them apart. E.g. call the link button in
column 1 lnkCol1 and then give the <asp:CheckBox /> in the corresponding
TemplateField an ID of chkCol1. When the page is built, ASP.NET will munge
the control names to prevent duplicates, of course, but that doesn't
matter - there will be enough to uniquely identify each checkbox. Then
include an extra argument in the client-side JavaScript function, e.g.

function CheckAll(colID)
{
for(i = 0; i <
document.getElementById('<%=MyGridView.ClientID%>').length; i++)
{
objElement = document.forms[0].elements;
if (objElement.type == 'checkbox' && objElement.id.indexOf(colID)
{
objElement.checked = true;
}
)

Finally, in the markup for the LinkButtons, add e.g.
OnClientClick="CheckAll('Col1');"

Obviously, the first solution is more efficient because it does not need to
walk through the entire collection of elements behind which comprise the
HTML rendered from the GridView, but it involves more work to set up
initially. The second solution is much easier and quicker to code so, unless
the GridView contains a *HUGE* amount of checkboxes, that's the one I'd
almost certainly go for...
 
Almost working, where almost makes a big difference:)
"&& objElement.id.indexOf(colID) > -1" is this some kind of search
similar to "like" in sql?

Thank you for your help, I think I am getting closer.

Arek
 
Back
Top