Bind comma separated values to listbox in - ASPMANTRA | Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server AND WCF snippets and tutorial

Bind comma separated values to listbox in

In this article I am going to explain how to Bind comma separated values to listbox in in ASP.Net using C# and

I have created a table Tb_Technology:

Insert the dummy data into table:

 Insert into Tb_Technology(Technology) values(',Php,Java')

Add a webform to project. Drag and drop the require control (Listbox) from toolbox to webform.

HTML Markup:
  <fieldset style="margin-left: 40px;width:30%">
    <legend><strong>Bind comma separated values to CheckBoxList</strong></legend>
    <tr><td>Select Technology :</td><td>
        <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>

Add the namespace
C# code:
using System.Data;
using System.Data.SqlClient;
using System.Configuration; code
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Create sqlconnection
C# code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString()); code
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())

Bind the Listbox
Create a method to bind the comma separated text to Listbox and call it on page load.
C# code:
protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
    public void BindListBox()
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Tb_Technology", con);
            DataTable dt = new DataTable();
            if (dt.Rows.Count > 0)
                string listboxvalues = dt.Rows[0]["Technology"].ToString();
                foreach (string tech in listboxvalues.Split(','))
                    ListItem items = new ListItem();
                    items.Text = tech;
                    items.Value = tech;
        catch (Exception ex)
        { }      
    } code
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
        End If
    End Sub
    Public Sub BindListBox()
            Dim adp As New SqlDataAdapter("Select * from Tb_Technology", con)
            Dim dt As New DataTable()
            If dt.Rows.Count > 0 Then
                Dim listboxvalues As String = dt.Rows(0)("Technology").ToString()
                For Each tech As String In listboxvalues.Split(","c)
                    Dim items As New ListItem()
                    items.Text = tech
                    items.Value = tech
            End If
        Catch ex As Exception
        End Try
    End Sub

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.