.comment-link {margin-left:.6em;}
Books & Articles I wrote.

Monday, February 27, 2006

 

DataBinding tips in .Net 2.0

Couple of things to watch when using databinding in .Net 2.0 (one actually applied to .Net 1.1 and i'd forgotten).

1. OnItemCreated doesn't fire if you are populating data from ViewState.

So if you are in a master/detail scenario whereby a second DetailsView (for example) is populated after you click an item in the parent GridView (for example), then if you are using the OnItemCreated event, you will find it will be executed as soon as the DetailsView is written, but after clicking on items in the GridView, the OnItemCreated event will not be processed.

So, if you have a DropDownList and want to set it to the value of the child item that has been selected, you cannot put the selection code into the OnItemCreated event as it will only select the initial value on the first databind and not on subsequent binds for each click! You need to move that code into the OnItemBound() event and hey presto, everything works great.

2. You can't use multiple ControlParameters in an ObjectDataSource when referring to a GridView.

This really is a pain and i can only assume there is some great reason behind it (which i am trying to discover). In short, the binding will actually only use the FIRST ControlParameter you refer to on both occassions - very odd indeed. To solve this issue, just use Parameter types and do something like the following in the code behind:


protected void GridView1_Select(object sender, EventArgs e)
{
GridView gv = (GridView)sender;
if (gv.SelectedRow != null)
{
ucContactListDetail.SelectParameters["UserID"].DefaultValue = gv.SelectedRow.Cells[0].Text;
ucContactListDetail.SelectParameters["ContactID"].DefaultValue = gv.SelectedRow.Cells[1].Text;
}
}

This page is powered by Blogger. Isn't yours?

Weblog Commenting and Trackback by HaloScan.com