我想做一个二级联动下拉菜单,不要求无刷新,想法是这样的。当我选择第一个中的项的时候,第二个下拉就根据第一个的值去添加。现在的问题是,我选择第一个的时候,就报错,说是id无效,我调试断点了一下,发现当我选择改变第一个的时候,就响应了ddl_areaBig_SelectedIndexChanged()事件,然后我的 this.ddl_areaBig.SelectedValue的就为空了。所以SQL语句就不能执行,造成我的第二个下拉就不能显示值。希望大家帮我解答一下。下面是这两个的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("order.mdb");
OleDbConnection con = new OleDbConnection(strCon);
con.Open();
OleDbDataAdapter oda = new OleDbDataAdapter();
oda.SelectCommand = new OleDbCommand("select distinct id,dealer,areaBig from dealer", con);
DataSet ds = new DataSet();
oda.Fill(ds, "dealer");
try
{
this.ddl_dealer.DataSource = ds.Tables["dealer"].DefaultView;
this.ddl_dealer.DataTextField = "dealer";
this.ddl_dealer.DataValueField = "id";
this.ddl_dealer.DataBind();
this.ddl_areaBig.DataSource = ds.Tables["dealer"].DefaultView;
this.ddl_areaBig.DataTextField = "areaBig";
this.ddl_areaBig.DataValueField = "id";
this.ddl_areaBig.DataBind();
}
catch (Exception ex)
{
//Response.Write(ex);
Response.Write("<script>window.alert('数据读取失败,请稍后再试...');</script>");
}
OleDbDataAdapter odaChild = new OleDbDataAdapter();
odaChild.SelectCommand = new OleDbCommand("select id,areaSmall from dealer where id=" + this.ddl_areaBig.SelectedValue, con);
DataSet dsChlid = new DataSet();
odaChild.Fill(dsChlid, "areaSmall");
foreach (DataRow row in dsChlid.Tables["areaSmall"].Rows)
{
this.ddl_areaSmall.Items.Add(new ListItem(row["areaSmall"].ToString(), row["id"].ToString()));
}
con.Close();
}
}
protected void ddl_areaBig_SelectedIndexChanged(object sender, EventArgs e)
{
this.ddl_areaBig.Items.Clear();
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("order.mdb");
OleDbConnection con = new OleDbConnection(strCon);
con.Open();
OleDbDataAdapter oda = new OleDbDataAdapter();
oda.SelectCommand = new OleDbCommand("select id,areaSmall from dealer where id=" + this.ddl_areaBig.SelectedValue,con);//就是这里页面打开的时候能取到值,当我再次选择第一个下拉列表的时候,他就不能取到值了。
DataSet ds = new DataSet();
oda.Fill(ds,"areaSmall");
foreach(DataRow row in ds.Tables["areaSmall"].Rows)
{
this.ddl_areaSmall.Items.Add(new ListItem(row["areaSmall"].ToString(),row["id"].ToString()));
}
con.Close();
}
谢谢大家!!!