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.

 
   1:   
   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");
   7:   
   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:  }
  13:   
  14:  // Handles the Selected Index changed event. 
  15:  void DropDownListQuantity_SelectedIndexChanged(object sender, EventArgs e)
  16:  {
  17:      
  18:      DropDownList dropdown = (DropDownList)sender;
  19:   
  20:      // Cast the parent to type RepeaterItem
  21:      RepeaterItem repeaterRow = (RepeaterItem)dropdown.Parent;
  22:   
  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");
  27:      
  28:      // Parse this string into an integer
  29:      int itemId = int.Parse(LiteralItemId.Text);
  30:      
  31:      //You can do some error handling here if the parse doesn't work..
  32:      
  33:      
  34:      // Get the value from the dropdown list.
  35:      int newQuantity = int.Parse(dropdown.SelectedValue);
  36:      
  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.
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):