Get ListControl values (CheckBoxList, RadioButtonList, DropDownList, ListBox) from a Repeater the easy way (ASP.NET C#)

Building on Get TextBox values from a Repeater the easy way (ASP.NET C#), here is a function that will get the selected values from WebControls that inherit from ListControl (CheckBoxList, RadioButtonList, DropDownList and ListBox)

It returns null if the ListControl matching the given ID does not exist in the repeater or an empty string array if nothing is selected.

public string[] ListControlValues(RepeaterItem itm, string controlId)
{
 string[] output = null;
 ListControl t = itm.FindControl(controlId) as ListControl;
 if (t != null)
 {
  ArrayList ar = new ArrayList();
  foreach (ListItem li in t.Items)
  {
   if (li.Selected) ar.Add(li.Value);
  }
  output = (string[])ar.ToArray(typeof(string));
 }
 return output;
}

Use in Repeater ItemCommand

protected void MyRepeater_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
 switch (e.CommandName.ToString())
 {
  case "Save":
   int recordID = Convert.ToInt32(e.CommandArgument);
   string[] listBoxValues = ListControlValues("ListBox1");
   if(listBoxValues != null)
   {
     foreach(string s in listBoxValues)
     {
      
     }
   }
   string[] dropDownValues = ListControlValues("DropDown1");
   if(dropDownValues != null)
   {
    // since dropdown can only have one item selected...
    string dropDownValue = dropDownValues[0];
   }
   ....
   
   break;
  default:
   break;
 }
}

Comments

Popular posts from this blog

Select box manipulation with jQuery

iTextSharp: Generating a Basic PDF file (ASP.NET/C#)

Popup Window Countdown (JavaScript)