Why Update and Cancel events were not firing on dynamically added Datagrid on the place holder control?

 

Recently i got a case where customer was creating and intializing ASP.NET Data grid dynamically on a button click and was adding it inside the placeholder control. After doing that he was not able to fire edit and cancel commands on the Datagrid. After the troubleshooting we found that he was binding the datagrid first and then adding it to placeholder control and that was the problem. Let's understand, why that was causing the problem.

This is because when we add child control in the parent control’s collection (In our case it is Place holder control), added child control’s TrackViewState() method is automatically called. But, only those items added to the view state, after the view state has started being tracked, will be recorded. So binding the Datagrid, prior to adding it to Place holder control collection causes those additions not to be saved in the view state for Datagrid. Rather we need to first add the Datagrid to Place holder and then bind the Datagrid.

We can easily check the behavior by comparing the view states in both of the conditions i.e. we will find the size for view state very less, when Datagrid is bound first and then added to placeholder.

For more information on dynamically adding controls visit the following url http://msdn.microsoft.com/asp.net/default.aspx?pull=/library/en-us/dnaspp/html/DynamicUI.asp