Saturday, 8 November 2014

Bind Asp.net Dropdownlist from database in C#, VB.net

Introduction: Here I will explain how to bind dropdownlist from database.
Description: Today I will show you how to bind dropdownlist static and from database also I will
explain you how to find data in dropdownlist by text and by value.
Before implement this example we need database

Column NameDataTypeAllowNulls
UserId Int(set identity true) No
UserName VarChar(50) Yes
Location VarChar(50) Yes

Once table is designed write below code to your aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>how to show data in dropdownlist from database in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<b>Selected UserName:</b>
<asp:DropDownList ID="ddlUser" runat="server" />
</div>
</form>
</body>
</html


Now add the following namespace to code behind

C# code


using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

After add namespace write the following code to code behind

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindUserdropdown();
}
}
/// <summary>
/// Bind Userdropdown
/// </summary>
protected voidBindUserdropdown ()
{
//conenction path for database
using (SqlConnection con = new SqlConnection("Data Source=Manoj;Integrated Security=true;Initial Catalog=MySchool"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserId,UserName FROM UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlUser.DataSource = ds;
ddlUser.DataTextField = "UserName";
ddlUser.DataValueField = "UserId";
ddlUser.DataBind();
ddlUser.Items.Insert(0, new ListItem("--Select--", "0"));
con.Close();
}
}
VB.Net Code 
 
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Partial Class VBSample
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindUserdropdown()
End If
End Sub
''' <summary>
''' Bind UserDropdownlist
''' </summary>
Protected SubBindUserdropdown ()
'conenction path for database
Using con As New SqlConnection("Data Source=Manoj;Integrated Security=true;Initial Catalog=MySchool")
con.Open()
Dim cmd As New SqlCommand("Select UserId,UserName FROM UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
ddlUser.DataSource = ds
ddlUser.DataTextField = "UserName"
ddlUser.DataValueField = "UserId"
ddlUser.DataBind()
ddlUser.Items.Insert(0, New ListItem("--Select--", "0"))
con.Close()
End Using
End Sub
End Class
 

No comments:

Post a Comment