Bind a DropDownList control with database in VB.NET
This article describes how to bind DropDownlist control with database.
This article describes how to bind DropDownlist with database and also display binding data in GridView. To do that we create a table in sql server database and insert some record in the table. after that we select item in the DropDownList and match with database table which record match with database. it will display in the GridView control.
Creating connection object
To create a connection we pass the connection string as a parameter in connection object.
Dim str As String = "Data Source=.;uid=sa;pwd=123;database=master"
Dim con As New SqlConnection(str)
The above string defines the connection string which is used to connect the database with the application.
Now we create a database table and insert some values in this table. Table looks like this.
create table logn
(
username varchar(50),
password varchar(40)
)
go
insert into logn values('monu','mohan')
go
insert into logn values('Rohatash','rohit')
go
insert into logn values('Manoj','singh')
go
select * from logn;
The table looks like this.
OUTPUT
Table1.gif
Using select statement with DropDownList
Dim cmd As New SqlCommand("select * from logn where username = '" + DropDownList1.SelectedItem.Text + "'", con)
Binding data with DropDownList
To bind the data from database to GridView control use DataSource property. The DataSource property is used for displaying data.
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
For example
Drag and Drop one GridView control, one Button control and one DropDownList control on the form. The form looks like this.
Figure1.gif
Now double click on the Button control and add the following vb.net code.
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim str As String = "Data Source=.;uid=sa;pwd=123;database=master"
Dim con As New SqlConnection(str)
Dim cmd As New SqlCommand("select * from logn where username = '" + DropDownList1.SelectedItem.Text + "'", con)
Dim Adpt As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
If (Adpt.Fill(ds, "logn")) Then
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
Label1.Text = "record found"
Else
Label1.Text = "Record not found"
End If
End Sub
End Class
Now run the application and select the name from DropDownList control and click on the Button.
Figure2.gif
Now click on the Button.
Figure3.gif