Got C# Corner MVP Award


Feeling Excited to announce that today i have got the most awaited MVP Award from C# Corner. An online community for computer professionals.

Thanks to C# Corner.

07042016081103AM

Advertisements

Get Multiple Selected Values From ASP CheckBoxList


Today we will learn how to get multiple checkbox values from ASP checkboxlist in two ways. ASP checkbox list  is very useful when we have multiple values that need to be listed against any one heading.
First Way: (Normal Single Values)
You can select this way and get non-comma separated normal values one by one by looping the list items and print its values
as you can see in the following image,
This is best suited when you want to do operation on more than 1 values to bind the checked values (retrieve values from database or suited to your case).
  1. <asp:CheckBoxList ID=“chklistcolors” runat=“server”>
  2.                 <asp:ListItem Text=“White”>White</asp:ListItem>
  3.                 <asp:ListItem Text=“Black”>Black</asp:ListItem>
  4.                 <asp:ListItem Text=“Green”>Green</asp:ListItem>
  5.                 <asp:ListItem Text=“Yellow”>Yellow</asp:ListItem>
  6.                 <asp:ListItem Text=“Red”>Red</asp:ListItem>
  7.                 <asp:ListItem Text=“Pink”>Pink</asp:ListItem>
  8.                 <asp:ListItem Text=“Orange”>Orange</asp:ListItem>
  9.                 <asp:ListItem Text=“Gray”>Gray</asp:ListItem>
  10.                 <asp:ListItem Text=“Blue”>Blue</asp:ListItem>
  11.                 <asp:ListItem Text=“Purple”>Purple</asp:ListItem>
  12. </asp:CheckBoxList>
Here is the code that do the functionality,
  1.         lblvalues.Text = “”;
  2.         foreach (ListItem lst in chklistcolors.Items)
  3.         {
  4.             if (lst.Selected == true)
  5.             {
  6.                 lblvalues.Text += “Selected Item Text: “ + lst.Text + “<br />”;
  7.             }
  8.         }

In the above code value can be get from list items printed to the label to check the selected values.

Second way: (Comma Separated Values)
This is if you want to insert into the database with comma separated values or want to get some required value by separating the checklist values to do some trick.
The code for the second option is:
  1.  lblvalues.Text = “”;
  2.  string selectedItems = String.Join(“,”,
  3.   chklistcolors.Items.OfType<ListItem>().Where(r => r.Selected)
  4.  .Select(r => r.Text));
  5.  lblvalues.Text = selectedItems;

By using this optimized way of code you don’t need to slice the last index of  values.

Full code is attached and you can find it on Github as well.