title: DataList Set SelectedIndex from DataKey Value
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>How can i set the appropriate SelectedIndex of the DataList from this DataKey value?</p>
  
  <p>I have tried the following;</p>
  
  <pre><code>      protected void dlCampChars_DataBinding(object sender, EventArgs e)
   {
    for (int i = 0; i &lt; 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 { }
    }
  }
  </code></pre>
  
  <p>If i set it in ItemDataBinding the SelectedIndex update is made after the DL has been bound and has no effect. Any ideas??</p>
  
  <p>Thanks</p>
  
  <p><strong>UPDATED CODE</strong></p>
  
  <pre><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 &lt; 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;
                    }
                   }
  </code></pre>