How to Display Comma Separated ListBox Items in ASP.NET

Introduction:

ListBoxes in ASP.NET provide a user-friendly way to select multiple items. In this tutorial, we'll explore how to retrieve and display the comma-separated text of selected items from a ListBox using C# code. Follow along as we create a simple web page demonstrating this functionality.

Creating the Page:

To get started, create an ASP.NET page with a ListBox, a Button, and a Label. The ListBox is set to allow multiple selections, and the Button is used to trigger the process. The Label will display the comma-separated text of the selected items.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListBox-with-Comma.aspx.cs" Inherits="Example_ListBox_with_Comma" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" 
            Width="325px">
            <asp:ListItem>Select</asp:ListItem>
            <asp:ListItem>Asia</asp:ListItem>
            <asp:ListItem>Europe</asp:ListItem>
            <asp:ListItem>North America</asp:ListItem>
            <asp:ListItem>South America</asp:ListItem>
            <asp:ListItem>Africa</asp:ListItem>
        </asp:ListBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add" 
            Width="84px" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>

C# Coding:

Now, let's delve into the C# code that processes the selected items when the button is clicked. The code iterates through the ListBox items, checks if an item is selected, and concatenates the selected items into a comma-separated string. This string is then displayed in the Label.


 protected void Button1_Click(object sender, EventArgs e)
    {
        if (ListBox1.SelectedItem.Text == "Select")
        {
            Label1.Text = "No Items Selected...";
        }
        else
        {
            string get_soft_skills = "";
            for (int i = 0; i < ListBox1.Items.Count; i++)
            {
                if (ListBox1.Items[i].Selected)
                {
                    get_soft_skills += ListBox1.Items[i].Value;
                    Label1.Text = get_soft_skills;
                    
                }
            }
             

        }
    }

Conclusion:

By following this tutorial, you've learned how to retrieve and display the comma-separated text of selected items from a ListBox in ASP.NET. This can be a useful feature in scenarios where you need to process and present multiple selections from users. Feel free to incorporate and adapt this code to enhance the functionality of your web applications.

Post a Comment

0 Comments