views:

436

answers:

4

How do you access the databound item after postback?

I have a datalist,and when the user selects an item, the OnItemCommand event fires, and my event handler looks liek this:

protected void dlResults_Select(object sender, DataListCommandEventArgs e)
{
  MyItem item = e.Item.DataItem as MyItem;
}

item is always null. Is there a way to access the databound item?

A: 

Hi, A few suggestions here.

keyboardP
A: 

The simplest approach I have found to this type of problem is to add a javascript event to the control which updates an input control (type=hidden) with the selected value of the control. If you add the runat=server attribute to the tag you can access the input control server side and read the value from it. The postback should fire after the javascript event so everything else should work 'normally' for you.

Mike
+1  A: 

The DataItem property is only not null when accessed through the ItemDataBound event. If you require an ID to modify your object/record you can set the DataKeyField property of the DataList to populate the DataKeys collection.

<asp:DataList ID="DataList1" runat="server" DataKeyField="id">
</asp:DataList>

You can then use the id in your OnItemCommand event to instantiate the desired object, or as a parameter to a database query.

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
    int id = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
    MyItem item = new MyItem(id);
}
Phaedrus
A: 

An appropriate answer to your question can only be provided after knowing the way you are doing the data binding. Are you doing the data binding from the code by calling the .DataBind() method of the datalist or are you providing a datasource to the datalist to bind from. The reason i ask this question is that in case you are using the .DataBind() method of the datalist from the code for binding the datalist, you will have to call it on every postback to make sure that the datalist gets databound again. Otherwise after the post back you will see that the datalist shows up empty. In case you are providing a datasource to the datalist to bind from, using its DataSource or DataSourceId property, the databinding of the datalist on each post back is taken care of by the framework, you don't have to be concerned about that.

But from the look of things i believe that you are getting the value as null because you are trying to get the value of the DataItem at a wrong place. Remember that you will have to follow the proper life cycle of a control to make it work for you the way you want it to work.

I can provide better answer if you can answer my queries above. Your current statement seems insufficient for providing a relevant answer.

Bootcamp