Hi rakesh.g11411,
Please refer below sample.
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="lstCustomers" runat="server" Height="100px" Width="203px"
OnSelectedIndexChanged="lstCustomers_SelectedIndexChanged" AutoPostBack="true" ></asp:ListBox>
<br />
<br />
Selected Item:
<br />
<asp:Label ID="lblEvents" runat="server" ></asp:Label>
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 5 CustomerID, ContactName FROM Customers"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
lstCustomers.DataSource = cmd.ExecuteReader();
lstCustomers.DataTextField = "ContactName";
lstCustomers.DataValueField = "CustomerID";
lstCustomers.DataBind();
con.Close();
}
}
}
}
protected void lstCustomers_SelectedIndexChanged(object sender, EventArgs e)
{
lblEvents.Text = lstCustomers.SelectedItem.Text;
lstCustomers.Items.FindByText(lblEvents.Text).Selected = true;
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT TOP 5 CustomerID, ContactName FROM Customers")
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
lstCustomers.DataSource = cmd.ExecuteReader()
lstCustomers.DataTextField = "ContactName"
lstCustomers.DataValueField = "CustomerID"
lstCustomers.DataBind()
con.Close()
End Using
End Using
End If
End Sub
Protected Sub lstCustomers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
lblEvents.Text = lstCustomers.SelectedItem.Text
lstCustomers.Items.FindByText(lblEvents.Text).Selected = True
End Sub
Screenshot