DotNetSlackers: ASP.NET News for lazy Developers

Wednesday, August 3, 2011

Populate DropDown List from Database in ASP.NET & C#

It is often useful to allow users to select items from a dropdown list for input into a web form. However, this can be somewhat too limiting in certain situations.
This tutorial will show how we can dynamically populate a dropdown menu with records from a database.
First, we start by declaring the assembly reference:

using System.Data.SqlClient;

In our Web.config, we declare the connection string:
<appSettings>
<add key="ConnString" value="Data Source=CLIENT-TASK2\SQLEXPRESS;Initial Catalog=BasicDataAccess;Integrated Security=True"/>
</appSettings>

I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.


The ASPX page will look something like this:

<form id="form1" runat="server">
<div align="center">
<table><tr><th>Name:</th><td><asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList></td></tr>
<tr><th>City:</th><td><asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList></td></tr></table>
</div>
</form>

In the code-behind, we can create two methods and then call them on page load:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Populate1();
Populate2();
}

public void Populate1()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM [tblOne]", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();

SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();

DropDownList1.DataSource = ddlValues;
DropDownList1.DataValueField = "theName";
DropDownList1.DataTextField = "theName";
DropDownList1.DataBind();

cmd.Connection.Close();
cmd.Connection.Dispose();
}

public void Populate2()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM [tblOne]", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();

SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();

DropDownList2.DataSource = ddlValues;
DropDownList2.DataValueField = "theCity";
DropDownList2.DataTextField = "theCity";
DropDownList2.DataBind();

cmd.Connection.Close();
cmd.Connection.Dispose();
}
}

No comments:

Post a Comment