Hi nauna,
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:DropDownList runat="server" ID="ddlCountries" AppendDataBoundItems="true" Width="150px">
<asp:ListItem Text="Select" Value="0" Selected="True" />
</asp:DropDownList>
<asp:TextBox runat="server" ID="txtCountry" AutoPostBack="true" OnTextChanged="CountryChange" Width="150px" />
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 (!IsPostBack)
{
BindCountries();
}
}
protected void CountryChange(object sender, EventArgs e)
{
ddlCountries.ClearSelection();
ddlCountries.Items.Add(new ListItem { Text = txtCountry.Text.Trim(), Value = txtCountry.Text.Trim(), Selected = true });
}
private void BindCountries()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT DISTINCT Country FROM Employees";
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
ddlCountries.DataSource = dt;
ddlCountries.DataTextField = "Country";
ddlCountries.DataValueField = "Country";
ddlCountries.DataBind();
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindCountries()
End If
End Sub
Protected Sub CountryChange(ByVal sender As Object, ByVal e As EventArgs)
ddlCountries.ClearSelection()
ddlCountries.Items.Add(New ListItem With {.Text = txtCountry.Text.Trim(), .Value = txtCountry.Text.Trim(), .Selected = True})
End Sub
Private Sub BindCountries()
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = "SELECT DISTINCT Country FROM Employees"
Dim cmd As SqlCommand = New SqlCommand(query)
Using con As SqlConnection = New SqlConnection(conString)
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As DataTable = New DataTable()
sda.Fill(dt)
ddlCountries.DataSource = dt
ddlCountries.DataTextField = "Country"
ddlCountries.DataValueField = "Country"
ddlCountries.DataBind()
End Using
End Using
End Using
End Sub
Screenshot