One of the big DataGrid mysteries is (or was, at least for me) the handling
of events triggered by controls from within a DataGrid cell and not dealt with
by the DataGrid. An example is handling of the
event of a
CheckBox Control with enabled
On the other hand than these non preset postback controls are button controls
with default postback and support of a command attribute for which the DataGrid
provides sufficient assistance.
If you, like me, found that using a
DataGrid is one of the most convenient ways to handle any data-driven web applications, you might
quite often have experienced its limitations. If you need to get things done quickly, you might not want to write an entire column
control yourself, but just use a
TemplateColumn. Within this
would probably want to use some web controls and of course take advantage of all their native features, including events. But this
doesn't work out quite as smoothly as it might sound. In the course of experimenting with controls inside a DataGrid, I experienced quite a
lot of odd runtime compiler errors till I ran across one of the most interesting and useful DataGrid events: the
What we want to do here is just hook a handler routine onto the
OnCheckedChanged event of
CheckBox Control. The
TemplateColumn with the
CheckBox might look like
the following example:
<asp:CheckBox ID="cbExample" AutoPostBack="true" runat="server">
The function for handling the event in the undelying code will look very
similar to this:
protected void OnChangeHandler(object sender, System.EventArgs e)
So where are we going to connect the handler and the control? If we put the registration directly inside the Control
while using code to support it, we will probably end up with a nice runtime compiler error. By
applying the idea of delegate registration from VisualStudio, we can just do it
at runtime. Using the
ItemCreated event of the DataGrid (see code below) works out best for me,
especially because I usually do a lot of other tweaking around like merging
footer cells and switching sorting symbols.
private void grid_ItemCreated( object sender,
ListItemType elemType = e.Item.ItemType;
if ((elemType == ListItemType.Item)||(elemType == ListItemType.AlternatingItem))
CheckBox cBox = (CheckBox) e.Item.FindControl("cbExample");
cBox.CheckedChanged += new EventHandler(OnChangeHandler);
Points of Interest
Handling DataGrid and related events is sometimes a cumbersome task, but the
DataGrid is still one of my favorite controls. I would be happy to hear your solutions to this kind of problem.
Particular points of interest: whether you simply placed a function call inside another DataGrid event, and why you
preferred this solution in your particular situation.
- First Post on 22 Apr 2004.
- Added a VS.net 2003 sample project on 29 May 2004.