How to Show ListBox Items Separate with Comma in ASP.NET



Hi Friends,
How to get comma separated Text of Selected ListBox items and Show / display in below Label. The below code will help you to get the comma separated value from a selected items in a list box,

Create Page

<%@ 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# : Code

 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;
                    
                }
            }
             

        }
    }
Tag : ASP.NET, ListBox
0 Komentar untuk "How to Show ListBox Items Separate with Comma in ASP.NET"

Back To Top