Selecting Datalist before Databinding
I am grappling with the following
- I wish to select an item from a DataList based on an attribute of a DataListItem in the List
As far as I know this must be done before I do myDataList.DataBind()
but I'm using the OnItemDataBound method to determine whether I should select a particular item, and this gets fired after the databinding... so the item doesn't gets selected until the following postback.
If I try to loop through the items of the DataList before databinding looking for the one to select, they have not been created yet, and also I cannot Databind twice, as the first call closes my DataReader.
Here is some of the code:
private void Page_Load(object sender, System.EventArgs e){
// Setting selected index really needs to be done here
if(!IsPostBack){
CategoryList.DataSource = ProductsDB.GetProductCategories();
CategoryList.DataBind();
}
}
protected void CategoryList_ItemDataBound(Object sender, DataListItemEventArgs e){
string paramCategoryID = Request.Params["CategoryID"];
// Check that the DataItem has been created, and the http Parameter exists
if(paramCategoryID != null && e.Item.DataItem != null)
// Check if the current DataItem is the one we want to select
if(((IDataRecord)e.Item.DataItem)["CategoryID"].ToString()==paramCategoryID )
CategoryList.SelectedIndex = e.Item.ItemIndex;
}
|