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.
Tuesday, November 2, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment