aspx事件
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="省时选择器.aspx.cs" Inherits="_922练习.省时选择器" %>
<!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">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" Height="29px"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="150px">
<asp:ListItem Value="0">----请选择省份----</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" Height="29px" Width="135px">
<asp:ListItem Value="0">----请选择市----</asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>
aspx.cs事件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace _922练习
{
public partial class 省时选择器 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//this.DropDownList1.Items.Add(new ListItem("----请选择省份----", "0"));
FillDownList();
}
}
private void FillDownList()
{
string connstr = "Data Source=WIN-10AFVI27V7T;Initial Catalog=921练习;Persist Security Info=True;User ID=sa;Password=admin";
using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from Table_1";
using (SqlDataReader reader = cmd.ExecuteReader())
{
#region
//this.DropDownList1.DataSource = reader;
//this.DropDownList1.DataTextField = "Pname";
//this.DropDownList1.DataValueField = "id";
//this.DropDownList1.DataBind();
#endregion
#region old method
ListItem li;
while (reader.Read())
{
string name = reader.GetString(reader.GetOrdinal("Pname"));
int id = reader.GetInt32(reader.GetOrdinal("Id"));
li = new ListItem(name, id.ToString());
this.DropDownList1.Items.Add(li);
}
#endregion
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string connstr = "Data Source=WIN-10AFVI27V7T;Initial Catalog=921练习;Persist Security Info=True;User ID=sa;Password=admin";
using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select id,Fname from Table_2 where Fid=@xxx";
SqlParameter paran = new SqlParameter("xxx", this.DropDownList1.SelectedValue);
cmd.Parameters.Add(paran);
using (SqlDataReader reader = cmd.ExecuteReader())
{
this.DropDownList2.DataSource = reader;
this.DropDownList2.DataTextField = "Fname";
this.DropDownList2.DataValueField = "id";
this.DropDownList2.DataBind();
}
}
}
}
}
}