Vivek Thakur

Chaotically Complex

  Home  |   Contact  |   Syndication    |   Login
  105 Posts | 1 Stories | 498 Comments | 65 Trackbacks

News



Archives

ASP.NET Ventures

Here is a very famous issue which almost every developer goes through: assume we have a databound control like a DataList/DataGrid with a nested Button inside it. We want to handle the Button's click event in our code. We can easily to so using OnItemCommand method  which raises ItemCommand event. We need to attach an event handler to this in our code.

The problem crops up when we tyr to bind data on every postback, like:

page_load()
{
    //..code//
BindDataControl();
}

Now, when the button control is clicked in the datalist/datagrid, it submits the form causing a postback. In the page_load the databind occurs again and all the information about any attached event handlers is lost as the control is bounded again which means that the nested button control will be re-created. This will cause the ItemCommand event handler not to fire.

Simple solution to this problem is to avoid re-binding of data on postback. For e.g.:

page_load()
{
    //..code//
if(!IsPostBack)
  {
      BindDataControl();
   }
}

This will make sure that nested controls are not re-created each time on postback and their "state" is maintained. This makes sure that the ItemCommand event handler is fired when ever the Button control is clicked.

 

posted on Friday, April 06, 2007 12:32 AM

Feedback

# Links (4/5/2007) 4/25/2007 9:40 PM Member Blogs
.NET Dependency Injection and a new version of RhinoMocks Jump Start State Machine Workflow .NET vNext

# re: ItemCommand events not firing for datalist 6/6/2008 3:16 PM Rohit Sinha
Great one Dude!!!

# re: ItemCommand events not firing for datalist 11/25/2008 8:51 AM Tom Wallace
Thanks a lot! This solved my problem.

# re: ItemCommand events not firing for datalist 4/29/2009 2:20 PM Jason
Thanks Mate, took the best part of day to find this solution. Ironic that it meant commenting out one line of code!

# re: ItemCommand events not firing for datalist 5/5/2009 12:18 PM Farhad
Thanks Dude! Solved My Problem...

# re: ItemCommand events not firing for datalist 10/2/2009 2:38 AM Ramya
Wonderful post! I was stuck with this problem for one whole day. Thanks a lot.

# re: ItemCommand events not firing for 10/29/2009 9:36 AM Hi
Wonderful post!

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: