作者:追风 来自:网络
下面的例子演示了利用DataReader从数据库中读出两个表,生成两个下拉列表的情况.
1.aspx文件:
<%@ Page language="c#" Codebehind="dropdown.aspx.cs" AutoEventWireup="false" Inherits="study.dropdown" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>dropdown</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="dropdown" method="post" runat="server">
Shirt Color:<asp:DropDownList id="shirtColorOptions" DataTextField="Color" runat="server"></asp:DropDownList>
Site Options:<asp:DropDownList id="shirtSizeOptions" DataTextField="Size" runat="server"></asp:DropDownList>
</form>
</body>
</HTML>
2.aspx.cs文件:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace study
{
/// <summary>
/// dropdown 的摘要说明。
/// </summary>
public class dropdown : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DropDownList shirtColorOptions;
protected System.Web.UI.WebControls.DropDownList shirtSizeOptions;
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
string strConn = "user id=sa;password=;initial catalog=dotasp;data source=jeff";
SqlConnection Conn = new SqlConnection(strConn);
Conn.Open();
string SQL;
SqlCommand dbComm;
SqlDataReader dbRead;
sql="select * from Color order by Color";
dbComm=new SqlCommand(SQL,Conn);
dbRead=dbComm.ExecuteReader();
while(dbRead.Read())
{
shirtColorOptions.Items.Add(new ListItem(dbRead["Color"].ToString()));
}
dbRead.Close();
sql="select * from Size order by Size";
dbComm=new SqlCommand(SQL,Conn);
dbRead=dbComm.ExecuteReader();
while(dbRead.Read())
{
shirtSizeOptions.Items.Add(new ListItem(dbRead["Size"].ToString()));
}
dbread.close();
Conn.Close();
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}