Recently I needed to have a DataGrid that had multiple checkboxes to activate and deactivate something. So, you could check a whole slew of checkboxes in a big grid, and depending on the NEW state of the checkbox (checked or not), cause an operation on a theorectical back end.
Here's some opinion/thought/zen on the DataGrid, and DataGridGirl will have to tell you if I'm wrong or not.
I needed to know when the checkbox changed, then act on it. So I remembered the order of events during a postback (and you should too):
So, I'd get a bunch of CheckBox_Changed events, and finally a Button_Click (from an 'Update' button).
In the Changed events I loaded a page-scoped ArrayList of things to act on, like, ProductIdsToActivateArrayList or ProductIdsToDeleteArrayList, depending on how many columns in my grid had checkboxes. As the Changed events fire, I just wanted to load up the ProductIDs for that CheckBox's row. But, how to avoid running around in the control tree? (which is, as I said before, gross)
I needed the data to come 'along for the ride' with the CheckBox_Changed Events. So in the .ASPX page:
<ItemTemplate><asp:CheckBox id='checkbox' ProductId='<%#DataBinder.Eval(Container.DataItem, "ProductID")%> OnChecked='CheckBoxChanged'>
Notice that! A totally random and unknown attribute in the CheckBox's statement. Is that allowed? How will it render? Well, it is allowed (although VS.NET's Designer will complain).
It renders, interestingly enough, like this:
<span ProductId="4"><input type="checkbox" id="checkbox" name="checkbox"></span>
Look at the extra span! Crazay. Then in the CheckBoxChanged event on the server-side after someone clicks a bunch of CheckBoxes and clicks Update:
public void CheckBoxChanged(object sender, EventArgs e){ string ProductID = ((CheckBox)sender).Attributes["ProductID"]).ToString(); ProductsToDeleteArrayList.Add(ProductID);}
Then in the Button_Click event (remember, that happens AFTER all this) I spin through the ArrayLists (there are several, one for each action) and perform the actions in a batch. This makes the Button_Click code CLEAN. It makes the CheckBoxChanged code CLEAN, and it bypasses a whole lot of running around in the control tree.
Also, before I forget: Congratulations to Robert for the birth of the definitive Scrolling Data Grid. Kudos.
Ads by The Lounge