Populate Database Column in a Dropdownlist in asp.net

Description:-

In this article we will populate table column inside Dropdownlist control using database connection. here you can see i have created a database connection and get data from database using command inside page_load event. here is the demo example to bind column inside dropdownlist control.

Create Table:-
CREATE TABLE [dbo].[Employee](
                [Emp_Id] [bigint] IDENTITY(1,1) NOT NULL,
                [Emp_Name] [varchar](50) NOT NULL,
                [Emp_Photo] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Employee_1] PRIMARY KEY CLUSTERED
(
                [Emp_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
 
GO

Web.Config:-
<connectionStrings>
    <add connectionString="ConnectionString" name="DBCS" providerName="System.Data.SqlClient"/>   
</connectionStrings>

Default.aspx:-
<div>
  <asp:Label ID="lbluser" runat="server" Text="User Name"></asp:Label>
  <asp:DropDownList ID="drpusername" runat="server"></asp:DropDownList>
</div>

Default.aspx.cs:-
string Str = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
  SqlConnection con = new SqlConnection(Str);
  SqlCommand cmd = new SqlCommand("Select Emp_Name from Employee", con);
  cmd.CommandType = CommandType.Text;
  SqlDataAdapter da = new SqlDataAdapter();
  da.SelectCommand = cmd;
  DataTable dt = new DataTable();
  da.Fill(dt);
  drpusername.DataSource = dt;
  drpusername.DataTextField = "Emp_Name";
  drpusername.DataValueField = "Emp_Name";
  drpusername.DataBind();
}

Related Posts

Thanks for comments.....

:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:P
:o
:>)
(o)
:p
:-?
(p)
:-s
(m)
8-)
:-t
:-b
b-(
:-#
=p~
$-)
(y)
(f)
x-)
(k)
(h)
cheer