Click here to Skip to main content
Licence 
First Posted 21 Apr 2004
Views 192,331
Bookmarked 46 times

Handling events of child controls inside a DataGrid

By | 2 Jun 2004 | Article
How to hook up on an event of a web control residing inside a DataGrid cell.

Introduction

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 OnCheckedChanged event of a CheckBox Control with enabled AutoPostBack. 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.

Background

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 TemplateColumn, you 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 ItemCreated event.

How-To

What we want to do here is just hook a handler routine onto the OnCheckedChanged event of the CheckBox Control. The TemplateColumn with the CheckBox might look like the following example:

<asp:TemplateColumn HeaderText="Checkbox"> 
 <ItemTemplate> 
   <asp:CheckBox ID="cbExample" AutoPostBack="true" runat="server"> 
   </asp:CheckBox> 
 </ItemTemplate> 
</asp:TemplateColumn> 

The function for handling the event in the undelying code will look very similar to this:

 protected void OnChangeHandler(object sender, System.EventArgs e)
 { 
  // Handle the event...
 } 

So where are we going to connect the handler and the control? If we put the registration directly inside the Control such as OnCheckChanged="OnChangeHandler" 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, 
  System.Web.UI.WebControls.DataGridItemEventArgs e) 
 { 
  ListItemType elemType = e.Item.ItemType;
  if ((elemType == ListItemType.Item)||(elemType == ListItemType.AlternatingItem)) 
  { 
   // *** Event Handler for Checkbox *** 
   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.

History

  • First Post on 22 Apr 2004.
  • Added a VS.net 2003 sample project on 29 May 2004.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

mkruppa

Team Leader

Germany Germany

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questioncan i have this code in vb.net Pinmembermalikamjad2:14 5 Jul '06  
AnswerRe: can i have this code in vb.net PinmemberRupesh Mhatre21:15 18 Nov '07  
GeneralAlternatively you could do this Pinmembersachinsrb0:03 22 Dec '05  
GeneralRe: Alternatively you could do this PinmemberMika23:48 24 Apr '06  
GeneralObject reference not set to an instance of an object PinsussAnonymous4:48 12 Oct '05  
GeneralThanks Pinmemberhsu_kf21:11 12 Jul '05  
QuestionMabye you know, what I'm doing wrong? Pinmemberthomasa22:43 24 Apr '05  
I have an asp.net page with a DataGrid like:
 
<asp:datagrid id="dgAddresses" runat="server" CssClass="grid" GridLines="None" AutoGenerateColumns="False">
 
I've created a TemplateColumn with a ImageButton:
<asp:TemplateColumn ItemStyle-VerticalAlign="Top">

<asp:ImageButton id="ibtnViewConnections" runat="server" CommandArgument='<%DataBinder.Eval(Container.DataItem, "lngAddressID").ToString()%>'>



 
in my .cs file I've added an
this.dgAddresses.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgAddresses_ItemCreated);
 
This method is:
 
private void dgAddresses_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView drv = (DataRowView)e.Item.DataItem;

if(drv != null)
{
//Has loaded data from database
System.Web.UI.WebControls.ImageButton ibtn = (System.Web.UI.WebControls.ImageButton)e.Item.Cells[0].Controls[1];
ibtn.Click += new System.Web.UI.ImageClickEventHandler(this.ibtnViewConections_Click);
 
}
 
else
{
System.Web.UI.WebControls.ImageButton ibtn = null;
ibtn = (System.Web.UI.WebControls.ImageButton)e.Item.Cells[0].Controls[1];
if(ibtn.CommandArgument != "")
{
ibtn.Click += new System.Web.UI.ImageClickEventHandler(this.ibtnViewConections_Click);
 
.........
 

 
At first run the DataGrid draws itself perfect, with all it's values.
 
When I hit the ImageButton, it goes directly in to the dgAddresses_ItemCreated(..) methode, but the ImageButton has no values ( the CommandArgument is "") or in other words the
"System.Web.UI.WebControls.DataGridItemEventArgs e" is empty.
 
I've thougt it should contain the data posted from the clint side.
 
What am I doing wrong? And how can I catch the data?
 

In the same page I have a Button and a TextBox (Outside the DataGrid) . When I hit det Button it goes direct to the "Page_Load(object sender, System.EventArgs e)" method, at this point the TextBox.Text is empty. Next method it enters is the Button_Click(object sender, System.EventArgs e), at this point the TextBox.Text has got it's value(from clint side). This is ofcourse what I want, but how did this happen? In regards of the ImageButton where it didn't happen.


 
Thanks in advance for all help
 
Thomas
Generalnever found a child control when usign Edit Templete Pinmembercarzel9:46 3 Feb '05  
QuestionHow about user controls? PinmemberJoe Cleland6:21 20 Jan '05  
GeneralUrgent please help. iTrying to implement it with a radiobuttonlist and vb.net Pinmemberluisvalencia9:24 5 Jan '05  
GeneralOnCheckChanged="OnChangeHandler" - will work Pinsussrabashani6:16 6 Nov '04  
GeneralRe: OnCheckChanged="OnChangeHandler" - will work Pinmembermkruppa1:34 9 Nov '04  
GeneralNew header PinsussFernando Finelli5:12 23 Jul '04  
GeneralHaving trouble working your code on the event handler Pinmemberramjisk4:56 18 Jun '04  
GeneralRe: Having trouble working your code on the event handler Pinmembermkruppa6:17 18 Jun '04  
GeneralRe: Having trouble working your code on the event handler Pinmemberramjisk7:42 18 Jun '04  
GeneralRe: Having trouble working your code on the event handler Pinmembermkruppa11:00 18 Jun '04  
GeneralRe: Having trouble working your code on the event handler Pinmemberramjisk11:11 18 Jun '04  
GeneralRe: Having trouble working your code on the event handler Pinmemberramjisk7:51 18 Jun '04  
GeneralRe: Having trouble working your code on the event handler Pinmembermkruppa11:23 18 Jun '04  
GeneralRe: Having trouble working your code on the event handler Pinmemberramjisk3:11 21 Jun '04  
GeneralRe: Having trouble working your code on the event handler Pinmembermkruppa22:44 24 Jun '04  
Generalunruledboy PinmemberChen Huisheng2:31 3 Jun '04  
GeneralRe: unruledboy Pinmembermkruppa3:10 3 Jun '04  
GeneralRe: unruledboy PinmemberValeriyP7:22 4 Jun '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120528.1 | Last Updated 3 Jun 2004
Article Copyright 2004 by mkruppa
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid