Search code examples
c#asp.netwebformscheckboxlist

How to get value of CheckBoxList items other than text


I am a simple webforms which has CheckBoxList with multiple selection and i want to get value of items rather than text.

 <asp:CheckBoxList ID="ChkAreaOfInterest" runat="server" CssClass="row-dd" >
    <asp:ListItem Value="0" Selected="True">---SELECT OPTION--</asp:ListItem>
    <asp:ListItem Value="One">RED</asp:ListItem>
    <asp:ListItem Value="Two">GREEN</asp:ListItem>
    <asp:ListItem Value="Three">BLUE</asp:ListItem>
</asp:CheckBoxList>

I use below code to get the value but it gets me text of the Items

List<ListItem> selectedInterest = new List<ListItem>();
foreach (ListItem item in ChkAreaOfInterest.Items)
if (item.Selected) selectedInterest.Add(item);
string sCheckedValue = string.Join(",", selectedInterest);

Solution

  • When you string.Join(",", selectedInterest) - runtime will call .ToString() on every item in selectedInterest which in fact returns value of .Text property.

    Instead you need to join ListItem.Value properties values. This can be done with LINQ:

    var selectedInterest = ChkAreaOfInterest.Items.OfType<ListItem>().Where(i => i.Selected);
    var sCheckedValue = string.Join(",", selectedInterest.Select(i => i.Value));