Home > .net 2.0 > checks and balances

checks and balances

May 31, 2006

While this isn’t a political statement, it has been like our current government–searching hours for answers, but without a clue what they’re really looking for…

A customer wanted the ability to check all the checkboxes to “select all”… fair enough, the table could have 50+ entries and clicking them all sucked.

Do gridviews have this feature? Of course not. 😦

So, I googled and found a montage of weird solutions.
Using buttons to activate check and uncheck the boxes,
Injecting javascript to check and uncheck the boxes,
Using “tricks” (and a lot of code) to provide the solution.

Unfortunately, none of these met my expectations. The last thing I want to do is inject javascript (no, I’m not really sold on AJAX yet either :P) and I wanted to have the checkbox in the header (like example 3 above), but without the extensive coding. Yes, I like to have cake, and eat it too. So, here’s what I came up with was pretty simple once I just sat down and tinkered.

On the ASPX page, have a TemplateField that looks like (save the

This gives us the “header” checkbox that we’ll use to check everything and the row checkbox for individual selection.In our code-behind pages, we need to add the code for the “all_checked” event.

protected void all_checked(object sender, EventArgs e)
foreach (GridViewRow gvr in GridView1.Rows)
CheckBox allCheckBox = (CheckBox)GridView1.HeaderRow.FindControl(“allchecked_checkbox”);
CheckBox rowCheckBox = (CheckBox)gvr.FindControl(“row_checkbox”);if (allCheckBox.Checked == true)
rowCheckBox.Checked = true;
rowCheckBox.Checked = false;

Now, the one thing that I haven’t tested is what the overhead is for this… since it’s looping through each checkbox, there’s a weight there; however, it is only posting back once.From here, you could use the same method for swapping out images (some like to use images instead of standard checkboxes) or most anything else–and in about 15 lines of code-behind.

Categories: .net 2.0
%d bloggers like this: