mo.notono.us

Wednesday, March 11, 2009

ASP.NET 101 Reminder: ListControl.Text == ListControl.SelectedValue…

…and NOT ListControl.SelectedItem.Text

ListControl implements IEditableTextControl and thus ITextControl, which mandates the Text property.  For whatever reason (I’m sure it was a good one) the ASP.NET architects chose to make the Text property implementation get and set the ListControl.SelectedValue rather than ListControl.SelectedItem.Text.

 

Coincidentally, there is no ListControl.FindByText method: the following extension methods may come in handy:

/// <summary>
/// Performs a case insensitive comparison finding a ListItem by its text value, and selecting that item
/// </summary>
/// <param name="listControl">The list control</param>
/// <param name="text">The text to match</param>
/// <returns>The first matched, selected <see cref="SPListItem"/> or null if not found.</returns>
public static ListItem SelectFirstByText(this ListControl listControl, string text)
{
  // first clear any previous selection 
  listControl.SelectedIndex = -1;
		
  foreach (ListItem item in listControl.Items)
  {
    if (string.Equals(item.Text, text, System.StringComparison.OrdinalIgnoreCase))
    {
      item.Selected = true;
      return item;
    }
  }
  //if not found...
  return null;
}

/// <summary>
/// Performs a case insensitive comparison finding ListItems by their text value, and selecting those items
/// </summary>
/// <param name="listControl">The list control.</param>
/// <param name="text">The text to match.</param>
/// <returns>An integer array of matched indices.</returns>
public static int[] SelectByText(this ListControl listControl, string text)
{
  List matches = new List();
  // first clear any previous selection 
  listControl.SelectedIndex = -1;
  int i = 0;
  foreach (ListItem item in listControl.Items)
  {
    if (string.Equals(item.Text, text, System.StringComparison.OrdinalIgnoreCase))
    {
      item.Selected = true;
      matches.Add(i);
    }
    i++;
  }
  return matches.ToArray();
}

Labels: , , , , ,

0 Comments:

Post a Comment

<< Home