Hi sanjayjp13,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<asp:ListBox ID="lbCountries" runat="server" Width="200px" SelectionMode="Multiple">
</asp:ListBox>
<br />
<asp:Button Text="Get Selected Item" runat="server" OnClick="GetSelectedItem" />
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Text
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateCountries();
}
}
private void PopulateCountries()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT TOP 10 CustomerID,Country FROM Customers";
cmd.Connection = conn;
conn.Open();
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
lbCountries.DataSource = dt;
lbCountries.DataTextField = "Country";
lbCountries.DataValueField = "CustomerID";
lbCountries.DataBind();
}
conn.Close();
}
}
}
protected void GetSelectedItem(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (ListItem item in lbCountries.Items)
{
if (item.Selected)
{
sb.Append(item.Text + ",");
}
}
Response.Write(sb.ToString().Remove(sb.ToString().Length - 1));
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
PopulateCountries()
End If
End Sub
Private Sub PopulateCountries()
Using conn As SqlConnection = New SqlConnection()
conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using cmd As SqlCommand = New SqlCommand()
cmd.CommandText = "SELECT TOP 10 CustomerID,Country FROM Customers"
cmd.Connection = conn
conn.Open()
Dim dt As DataTable = New DataTable()
Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
da.Fill(dt)
lbCountries.DataSource = dt
lbCountries.DataTextField = "Country"
lbCountries.DataValueField = "CustomerID"
lbCountries.DataBind()
End Using
conn.Close()
End Using
End Using
End Sub
Protected Sub GetSelectedItem(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As StringBuilder = New StringBuilder()
For Each item As ListItem In lbCountries.Items
If item.Selected Then
sb.Append(item.Text & ",")
End If
Next
Response.Write(sb.ToString().Remove(sb.ToString().Length - 1))
End Sub
Screenshot
