Populate Database Column in a Dropdown List

Here I am explain about how to populate database column in a dropdown List.

Database Structure

Query:

  1. CREATE TABLE tbl_ins
  2. (  
  3.    UserID [int] IDENTITY(1,1) ,  
  4.    Username varchar(30),  
  5.    Password varchar(30),  
  6.    Address varchar(100),  
  7.    Mobile varchar(12),  
  8.    Email varchar(50)  
  9. )  
DB Design:

DB Design

So here am explain how to populate database value in dropdownlist.

Database Information

Database table

Default.aspx:

Code:
  1. <asp:Label ID=”lbluser” runat=”server” Text=”User Name”></asp:Label>  
  2. <asp:DropDownList ID=”drpusername” runat=”server”></asp:DropDownList>  
Screen Design:

user name

WEBCONFIG:

WEBCONFIG

Default.aspx.cs:

(Here bind the username column from database to dropdownlist).

Code:
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.    if(!IsPostBack)  
  4.    {  
  5.       SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[“userconnstring”].ConnectionString);  
  6.       con.Open();  
  7.       SqlCommand cmd = new SqlCommand(“Select UserName from tbl_ins”, con);  
  8.       SqlDataAdapter da = new SqlDataAdapter(cmd);  
  9.       DataTable dt = new DataTable();  
  10.       da.Fill(dt);  
  11.       drpusername.DataSource = dt;  
  12.       drpusername.DataTextField = “UserName”;  
  13.       drpusername.DataValueField = “UserName”;  
  14.       drpusername.DataBind();  
  15.    }  
  16. }  
Output:

user name table