Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Show Bind Data to Asp.net Dropdownlist from Database in C#, VB.NET

Oct 9, 2012
Introduction:

Here I will explain how to bind or show data in dropdownlist from database in asp.net using C#.net and VB.NET.

Description:

In previous posts I explained many articles relating asp.net, jQuery, SQL Server, JavaScript. Now I will explain how to bind or show data in dropdownlist from database in asp.net using C#.net and VB.NET.

Before implement this example first design one table UserInformation in your database as shown below

Column Name
Data Type
Allow Nulls
UserId
Int (set Identity=true)
No
UserName
varchar(50)
Yes
Location
Varchar(50)
Yes
Once table designed in database write the following code in 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="ddlCountry" runat="server" />
</div>
</form>
</body>
</html>
Now add the following namespaces in code behind

C# Code


using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
After add namespaces write the following code in code behind


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindContrydropdown();
}
}
/// <summary>
/// Bind COuntrydropdown
/// </summary>
protected void BindContrydropdown()
{
//conenction path for database
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserId,UserName FROM UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlCountry.DataSource = ds;
ddlCountry.DataTextField = "UserName";
ddlCountry.DataValueField = "UserId";
ddlCountry.DataBind();
ddlCountry.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
BindContrydropdown()
End If
End Sub
''' <summary>
''' Bind COuntrydropdown
''' </summary>
Protected Sub BindContrydropdown()
'conenction path for database
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
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)
ddlCountry.DataSource = ds
ddlCountry.DataTextField = "UserName"
ddlCountry.DataValueField = "UserId"
ddlCountry.DataBind()
ddlCountry.Items.Insert(0, New ListItem("--Select--", "0"))
con.Close()
End Using
End Sub
End Class
Demo

If you want to learn more dropdownlist articles check this


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

30 comments :

Unknown said...

hai

Vetri said...

Hi...
I am your fan. I used many of your coding samples in my projects.

But In recent days your articles are very simple and basic things.

Could you please started to post on advanced things like MVC4 articles....

thanks
Vetri

Unknown said...

Thanks Suresh.

K.Ramalingam said...

thanks....

Unknown said...

simply superb

Unknown said...

Nice One

Laura Arévalo said...

perfecto, lo mas sencillo que vi en la red, gracias

Anonymous said...

Ty!!!

Atul Enjoying with studies said...

Hi suresh i want to display date in dropdown one ddlfor year in which year should be display likewise month and date.
ex:20130501 data in my data base now in page load 2013 in ddlyear and june in dllmonth should be display.
how will i do this.

Anonymous said...

Thanks Friend

Unknown said...

thanks

Zimasa Yokwana said...

Very helpful, thanks.

Unknown said...

thanks , but i don't repeat the same item in droplistdown ,

such as the droplistdown contain cc ,cc ,cc ,cc , & i hope to see 1 cc not 3

how ?

thanks

सोमनाथ चतुर्वेदी said...

Dhanyvaad Guruji

Unknown said...

hello sir

how i bind drop down list with detail view .....

Mukesh Dutt said...
This comment has been removed by the author.
Mukesh Dutt said...

Thanks solution for add new item for drop list at zero index by the new keyword.

Anonymous said...

how to load country, state, city dropdown list on a gridview's inserting and updating mode using three tier architecture.
I want its solution immediately.

Unknown said...

Thanks solution for add new item for drop list

Anonymous said...

Thank you. This information was helpful.

Anonymous said...

if selected value filed column data type is varchar then how to chek it with same colun in another table(fk)?

Unknown said...

i have one doubt how to convert the Auto suggestion textbox value to Dropdown list

Unknown said...
This comment has been removed by the author.
Unknown said...

thanks very Nice

Kashyap Bhavsar said...

Thank you Sureshbhai....it is very useful for beginners.
Again thanks

Unknown said...

Thanks....

Unknown said...

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: Incorrect syntax near the keyword 'FROM'.
getting this error can any one help me out please....

Unknown said...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace class_71117
{
public partial class Employee : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Fill_Country();
Fill_Grid();
}
}
public void ClearControls()
{
txtname.Text = "";
txtaddress.Text = "";
txtage.Text = "";
ddlcountry.SelectedValue = "0";
}
public void Fill_Grid()
{
con.Open();
SqlCommand cmd = new SqlCommand("usp_emp_get", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
grd.DataSource = ds;
grd.DataBind();
}
else
{
grd.DataSource = null;
grd.DataBind();
}
}

public void Fill_Country()
{
con.Open();
SqlCommand cmd = new SqlCommand("usp_country_get", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
ddlcountry.DataValueField = "cid";
ddlcountry.DataTextField = "cname";
ddlcountry.DataSource = ds;
ddlcountry.DataBind();
ddlcountry.Items.Insert(0,new ListItem("--Select--","0"));
}
}

protected void btnsave_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("usp_emp_insert",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@name",txtname.Text);
cmd.Parameters.AddWithValue("@address", txtaddress.Text);
cmd.Parameters.AddWithValue("@age", txtage.Text);
cmd.Parameters.AddWithValue("@cid", ddlcountry.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
Fill_Grid();
ClearControls();
}

Unknown said...
This comment has been removed by the author.
Unknown said...

protected void grd_RowEditing(object sender, GridViewEditEventArgs e)
{
grd.EditIndex = e.NewEditIndex;
Fill_Grid();
}

protected void grd_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grd.EditIndex = -1;
Fill_Grid();
}

protected void grd_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox TBN = grd.Rows[e.RowIndex].FindControl("txtname1") as TextBox;
TextBox TBD = grd.Rows[e.RowIndex].FindControl("txtaddress1") as TextBox;
TextBox TBG = grd.Rows[e.RowIndex].FindControl("txtage1") as TextBox;
string IDD = grd.DataKeys[e.RowIndex].Value.ToString();

con.Open();
SqlCommand cmd = new SqlCommand("usp_emp_update", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@empid", IDD);
cmd.Parameters.AddWithValue("@name", TBN.Text);
cmd.Parameters.AddWithValue("@address", TBD.Text);
cmd.Parameters.AddWithValue("@age", TBG.Text);
cmd.ExecuteNonQuery();
con.Close();
grd.EditIndex = -1;
Fill_Grid();
ClearControls();
}

protected void grd_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string IDD = grd.DataKeys[e.RowIndex].Value.ToString();
con.Open();
SqlCommand cmd = new SqlCommand("usp_emp_delete", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@empid", IDD);
cmd.ExecuteNonQuery();
con.Close();
Fill_Grid();
}

protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList DDL = e.Row.FindControl("ddlcountry1") as DropDownList;
con.Open();
SqlCommand cmd = new SqlCommand("usp_country_get", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
DDL.DataValueField = "cid";
DDL.DataTextField = "cname";
DDL.DataSource = ds;
DDL.DataBind();
DDL.Items.Insert(0, new ListItem("--Select--", "0"));
}
}
}
}
}
}

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.