Remember to add the usual using directives at the start of the codebehind
[codesyntax lang=”csharp”]
using System.Data; using System.Data.SqlClient;
[/codesyntax]
For a DropDownList on your ASP.NET page with an ID of Category such a
[codesyntax lang=”html4strict”]
<asp:DropDownList ID="Category" runat="server"> </asp:DropDownList>
[/codesyntax]
The following in your code behind will bind data from an example Northwind database on SQL Server to the text and values of the DropDownList
[codesyntax lang=”csharp”]
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; namespace AppDevStuff { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { using(SqlConnection cnn = new SqlConnection("Data Source=YOURSERVERNAME; Database=Northwind; UID=YOURUSERNAME; PWd=YOURPASSWORD")) { SqlCommand cmd; SqlDataReader rdr; if (!Page.IsPostBack) { cmd = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories ORDER BY CategoryName;", cnn); cnn.Open(); rdr = cmd.ExecuteReader(); Category.DataSource = rdr; Category.DataTextField = "CategoryName"; Category.DataValueField = "CategoryID"; Category.DataBind(); } } } } }
[/codesyntax]