//html页面代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <fieldset> <asp:DropDownList ID="DropDownList1" runat="server">//DropDownList控件 </asp:DropDownList> </fieldset> </form></body>
</html>
===========================================================================
//后台代码
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 WebApplication2 { public partial class WebForm1 : System.Web.UI.Page { SqlConnection sqlConn = new SqlConnection("SERVER=.; USER ID=SA;PASSWORD=123456;DATABASE=MySchool");//连接数据库 protected void Page_Load(object sender, EventArgs e) {if (!IsPostBack) {
GetDropLost();
}
} //定义一个方法读取 数据库中的表 void GetDropLost() { sqlConn.Open(); string SQL = "SELECT * FROM Student"; SqlDataAdapter sda = new SqlDataAdapter(SQL, sqlConn); System.Data.DataSet ds = new DataSet(); sda.Fill(ds);//数据源绑定 DropDownList1.DataValueField = "StudentId";//必须绑定int类型,不写发布会出错 DropDownList1.DataTextField = "LoginPwd";//这才是要显示的字段 this.DropDownList1.DataSource = ds; this.DropDownList1.DataBind(); this.DropDownList1.Items.Insert(0, new ListItem("--请你选择--")); sqlConn.Close(); } } }