Loading ...

ASP.NET: Checkboxlist to string list | CodeAsp.Net

ASP.NET: Checkboxlist to string list

 /5
0 (0votes)

In this blog I will show how to get selected values of checkboxlist in ASP.NET. The selected value can be get by applying foreach iterator on checkboxlist items and then we can find the selected items. I decided to make an extension to do the same. Below is the code for it:

Control Extensions:

using System.Collections.ObjectModel;
using System.Linq;
using System.Web.UI.WebControls;

namespace Sample.Extensions
{
    public static class WebControlsExtension
    {
        public static string ToStringList(this CheckBoxList cbl)
        {
            const string separator = ",";
            var values = new Collection<string>();
            foreach (var objItem in cbl.Items.Cast<ListItem>().Where(objItem => objItem.Selected))
            {
                values.Add(objItem.Value);
            }
            return string.Join(separator, values);
        }
    }
}

Let's test the above extension with some sample code:

<%@ Page Language="C#" %>
<%@ Import Namespace="Sample.Extensions" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Title</title>
    <script type="text/javascript">
 
    </script>
</head>
<body>
    <form id="HtmlForm" runat="server">
    <asp:CheckBoxList ID="CheckBoxList1" runat="server">
        <asp:ListItem Text="One" Value="1"/>
        <asp:ListItem Text="Two" Value="2"/>
        <asp:ListItem Text="Three" Value="3"/>
        <asp:ListItem Text="Four" Value="4"/>
    </asp:CheckBoxList>
    <asp:Button runat="server" ID="SubmitButton" Text="Submit" 
        onclick="SubmitButton_Click" />
    <asp:Label ID="SelectedValuesLabel" runat="server" Text=""></asp:Label>
    </form>
</body>
</html>
<script runat="server">


    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        string selectedValues= CheckBoxList1.ToStringList();
        SelectedValuesLabel.Text = selectedValues;

    }
</script>

Above there is a checkboxlist, submit button and a lable. On clicking the button the selected values of checkboxelist will be displayed in a label in a comma separated form

 

Comments (no comments yet)

Top Posts