
<% @Import Namespace="System.Data.SqlClient" %>
<HTML>
	<HEAD>
		<title>获取服务器端数据库列表示例</title>
		<script language="C#" runat="server">
		
			// 注意本节数据库连接字符串
			string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer1"];
			
			void Page_Load(object sender, System.EventArgs e)
			{
				// 创建连接及执行数据库操作
				string db_query = "sp_helpdb";
				SqlCommand myCommand = new SqlCommand(db_query, new SqlConnection(ConnStr));
				myCommand.Connection.Open();
				SqlDataReader dr = myCommand.ExecuteReader();

				// 将数据库列表绑定到下拉列表控件(DropDownList)
				DropDownList1.DataSource = dr;
				DropDownList1.DataTextField = "name";
				DropDownList1.DataBind();

				// 关闭DataReader对象和数据库连接
				dr.Close();
				myCommand.Connection.Close();
			}
		
			void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
			{
				// 获取要打开的数据库名称
				string dbName = DropDownList1.SelectedItem.Text;
				// 生成新的数据库连接字符串
				ConnStr = ConnStr + "Database=" + dbName;
				// 打开连接
				SqlConnection myConn = new SqlConnection(ConnStr);
				myConn.Open();
				Label1.Text = myConn.Database;
				myConn.Close();		
			}
		
		</script>
	</HEAD>
	<body>
		<form id="Form1" method="post" runat="server">
			<h3>获取服务器端数据库列表示例</h3>
			请选择：
			<asp:DropDownList 
				id="DropDownList1" 
				runat="server" 
				AutoPostBack="True" 
				OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
			</asp:DropDownList><br><br>
			打开的数据库：
			<asp:Label id="Label1" runat="server">未打开</asp:Label>
		</form>
	</body>
</HTML>
