In this article I
am going to explain how to Bind comma separated values to listbox in
asp.net in ASP.Net using C# and VB.net
In the previous
article I have explained how to get comma separated values (data) from databaseand bind to checkboxlist in ASP.Net using C# and VB.net, how to insert multipleselected items of Listbox to database as comma separated in ASP.Net using C#and VB.net and how to generate alphabets A to Z in asp.net, VB.net.
Implementation:
I have created a table Tb_Technology:
Id
|
int
|
Technology
|
varchar(50)
|
Insert the dummy data into table:
Insert into
Tb_Technology(Technology) values('Asp.net,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>
<table>
<tr><td>Select
Technology :</td><td>
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
</td></tr>
</table>
</fieldset>
Add the namespace
C# code:
using System.Data;
using System.Data.SqlClient;
using
System.Configuration;
VB.net code
Imports System.Data
Imports
System.Data.SqlClient
Imports
System.Configuration
Create sqlconnection
C# code:
SqlConnection con
= new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
VB.net 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)
{
BindListBox();
}
}
public void BindListBox()
{
try
{
SqlDataAdapter
adp = new SqlDataAdapter("Select * from Tb_Technology", con);
DataTable
dt = new DataTable();
adp.Fill(dt);
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;
ListBox1.Items.Add(items);
}
}
}
catch (Exception ex)
{ }
}
VB.net code
Protected Sub Page_Load(sender As
Object, e As
System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindListBox()
End If
End Sub
Public Sub BindListBox()
Try
Dim
adp As New
SqlDataAdapter("Select * from
Tb_Technology", con)
Dim
dt As New
DataTable()
adp.Fill(dt)
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
ListBox1.Items.Add(items)
Next
End
If
Catch
ex As Exception
End Try
End Sub
No comments:
Post a Comment