I have a DataList displayed on a (Asp.Net3.5) page which the user can select from. The datakey value of the selected row is then stored in the database.
If the page should be revisited by the same user at some point in the future the selected datakey value is retreived from the DB. I would like to use this datakey value to highlight the corresponding row in the DataList.
How can i set the appropriate SelectedIndex of the DataList from this DataKey value?
I have tried the following;
protected void dlCampChars_DataBinding(object sender, EventArgs e)
{
for (int i = 0; i < dlCampChars.Items.Count; i++)
{
// Ignore values that cannot be cast as integer.
try
{
if (dlCampChars.DataKeys[i].ToString() == lSelection.ToString())
{
Label28.Text = i + "";
dlCampChars.SelectedIndex = i + 1;
}
}
catch { }
}
}
If i set it in ItemDataBinding the SelectedIndex update is made after the DL has been bound and has no effect. Any ideas??
Thanks
UPDATED CODE
// if stored DataKey exists loop through DataTable
// looking for the index of the item matching the DataKey
int itemIndex = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
// check the appropriate "DataKey" column name of the current row
if (dt.Rows[i]["cha_Key"].ToString() == lSelection)
{
// match found, set index and break out of loop
itemIndex = i;
break;
}
}
It seems things are a little backwards in DataList land, depending on when the item is rendered and which template it is in (check out the 1st link below for an explanation). The ItemDataBound approach is valid, but sometimes is a little quirky as described in that article. In the case you describe I believe the 2nd approach would work, where you can set the SelectedIndex property prior to the call to DataBind(). The steps are:
Here's an example:
void Page_Load(Object sender, EventArgs e)
{
// Load sample data only once, when the page is first loaded.
if (!IsPostBack)
{
dlCampChars.DataSource = CreateDataSource();
dlCampChars.DataBind();
}
}
private DataTable CreateDataSource()
{
// however you get your data and whatever the resulting object is
// for example: DataTable, DataView, etc.
DataTable dt = [relevant code here];
// retrieve the user's stored DataKey
string datakey = [retrieved datakey value from DB];
// if stored DataKey exists loop through DataTable
// looking for the index of the item matching the DataKey
int itemIndex = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
// check the appropriate "DataKey" column name of the current row
if (dt.Rows[i]["DataKey"].ToString() == datakey)
{
// match found, set index and break out of loop
itemIndex = i;
break;
}
}
// set SelectedIndex
dlCampChars.SelectedIndex = itemIndex;
// now return the DataSource (ie. DataTable etc.)
return dt;
}
You might find these articles helpful:
EDIT: added DataTable for loop code. The idea would be the same for whatever your actual datasource object is.