Introduction:
In this article you
will come to know how to bind dropdownlist in asp.net with database.
Implementation:
In the desgin (.aspx)
page desgin the struture as below: Add dropdown control on the webpage.
<asp:DropDownList ID="ddlState" runat="server">
</asp:DropDownList>
Write code in code
behind file to Bind Dropdown:
C#.Net code
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
SqlConnection con
= new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropdown();
}
}
private void BindDropdown()
{
SqlDataAdapter adp = new SqlDataAdapter("select * from Tb_STATE", con);
DataTable dt = new DataTable();
adp.Fill(dt);
ddlState.DataSource = dt;
ddlState.DataTextField = "STATE";
ddlState.DataValueField = "ID";
ddlState.DataBind();
ddlState.Items.Insert(0, new ListItem("--Select--", "0"));
con.Close();
adp.Dispose();
}
VB.Net Code
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConStr").ToString())
Private Sub BindDropdown()
Dim adp As New SqlDataAdapter("select * from Tb_STATE", con)
Dim dt As New DataTable()
adp.Fill(dt)
ddlState.DataSource = dt
ddlState.DataTextField = "STATE"
ddlState.DataValueField = "ID"
ddlState.DataBind()
ddlState.Items.Insert(0, New ListItem("--Select--", "0"))
con.Close()
adp.Dispose()
End Sub
Protected Sub Page_Load(sender As Object,
e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindDropdown()
End If
End Sub
0 comments:
Post a Comment