Saturday, 8 November 2014

Bind Dropdownlist from database in C#,

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="">
<head runat="server">
<title>how to show data in dropdownlist from database in</title>
<form id="form1" runat="server">
<b>Selected UserName:</b>
<asp:DropDownList ID="ddlUser" runat="server" />

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)
/// <summary>
/// Bind Userdropdown
/// </summary>
protected voidBindUserdropdown ()
//conenction path for database
using (SqlConnection con = new SqlConnection("Data Source=Manoj;Integrated Security=true;Initial Catalog=MySchool"))
SqlCommand cmd = new SqlCommand("Select UserId,UserName FROM UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ddlUser.DataSource = ds;
ddlUser.DataTextField = "UserName";
ddlUser.DataValueField = "UserId";
ddlUser.Items.Insert(0, new ListItem("--Select--", "0"));
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
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")
Dim cmd As New SqlCommand("Select UserId,UserName FROM UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
ddlUser.DataSource = ds
ddlUser.DataTextField = "UserName"
ddlUser.DataValueField = "UserId"
ddlUser.Items.Insert(0, New ListItem("--Select--", "0"))
End Using
End Sub
End Class

No comments:

Post a Comment