Friday, 04 June 2010
Handling the DropDownList SelectedIndexChanged event in a Repeater

This is more for my own reference more because I keep on forgetting how to do it and am constantly look it up all the time. If it helps you out, even better! And before you say "..but in MVC you can do it like this..". I know, but some of us still have to work with Webforms working with legacy apps. 

My main problem with DropDownLists in Repeater control examples on the net is they don't show you how to figure out which DropDownList in your Repeater list fired the SelectedIndexChanged event.

   2:  // This is bound to the ItemDataBound event on the repeater.
   3:  protected void RepeaterBasketItems_ItemDataBound(object sender, RepeaterItemEventArgs e)
   4:  {
   5:      DropDownList DropDownListQuantity = 
   6:          (DropDownList)e.Item.FindControl("DropDownListQuantity");
   8:      // hint after typing += you can hit TAB TAB in Visual 
   9:      // Studio for it to create the event handler for you.
  10:      DropDownListQuantity.SelectedIndexChanged 
  11:          += new EventHandler(DropDownListQuantity_SelectedIndexChanged);
  12:  }
  14:  // Handles the Selected Index changed event. 
  15:  void DropDownListQuantity_SelectedIndexChanged(object sender, EventArgs e)
  16:  {
  18:      DropDownList dropdown = (DropDownList)sender;
  20:      // Cast the parent to type RepeaterItem
  21:      RepeaterItem repeaterRow = (RepeaterItem)dropdown.Parent;
  23:      // Inside the RepeaterItem find a hidden Literal I 
  24:      // placed there which contains the Item Id of the row. 
  25:      // You could use the DataItem if this is being persisted
  26:      Literal LiteralItemId = (Literal)repeaterRow.FindControl("LiteralItemId");
  28:      // Parse this string into an integer
  29:      int itemId = int.Parse(LiteralItemId.Text);
  31:      //You can do some error handling here if the parse doesn't work..
  34:      // Get the value from the dropdown list.
  35:      int newQuantity = int.Parse(dropdown.SelectedValue);
  37:      // Over here you could put your update method. that uses itemid and new quantity.
  38:  }
All comments require the approval of the site owner before being displayed.
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):