Hi,
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;
}
}