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).
- <asp:CheckBoxList ID="chklistcolors" runat="server">
- <asp:ListItem Text="White">White</asp:ListItem>
- <asp:ListItem Text="Black">Black</asp:ListItem>
- <asp:ListItem Text="Green">Green</asp:ListItem>
- <asp:ListItem Text="Yellow">Yellow</asp:ListItem>
- <asp:ListItem Text="Red">Red</asp:ListItem>
- <asp:ListItem Text="Pink">Pink</asp:ListItem>
- <asp:ListItem Text="Orange">Orange</asp:ListItem>
- <asp:ListItem Text="Gray">Gray</asp:ListItem>
- <asp:ListItem Text="Blue">Blue</asp:ListItem>
- <asp:ListItem Text="Purple">Purple</asp:ListItem>
- </asp:CheckBoxList>
Here is the code that do the functionality,
- lblvalues.Text = "";
-
- foreach (ListItem lst in chklistcolors.Items)
- {
- if (lst.Selected == true)
- {
- lblvalues.Text += "Selected Item Text: " + lst.Text + "<br />";
- }
-
- }
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:
- lblvalues.Text = "";
- string selectedItems = String.Join(",",
- chklistcolors.Items.OfType<ListItem>().Where(r => r.Selected)
- .Select(r => r.Text));
- 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.