我有两个DropDownLists。一旦选择了DropDownList1值,DropDownList2将根据Dropdownlist1进行填充。
但是在页面刷新之后,dropdownlist1选择的值被更改为最顶层的值(DropDownList由数据库填充)。
的.aspx:
<asp:DropDownList ID="DropDownList1" runat="server" Width="300px" CssClass="makeselect" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True" AppendDataBoundItems="true">
</asp:DropDownList>
的.cs:
protected void Page_Load(object sender, EventArgs e) {
DataTable subjects = new DataTable();
if (Page.IsPostBack == false) {
using (SqlConnection con = new SqlConnection(constring)) {
SqlDataAdapter adapter = new SqlDataAdapter("SELECT VehicleMake FROM VehicleDB", con);
adapter.Fill(subjects);
con.Open();
DropDownList1.DataSource = subjects;
DropDownList1.DataTextField = "VehicleMake";
DropDownList1.DataValueField = "";
DropDownList1.DataBind();
con.Close();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) {
string makename = DropDownList1.SelectedItem.Value;
keepname = makename;
Response.Redirect("default.aspx?QSVehicleMake="+makename);
}
答案 0 :(得分:2)
您可以将SESSION值用于此目的,使用此值从下拉列表中查找项目
protected void Page_Load(object sender, EventArgs e)
{
jpyRATE = 1.4;
DataTable subjects = new DataTable();
if (Page.IsPostBack == false)
{
using (SqlConnection con = new SqlConnection(constring))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT VehicleMake FROM VehicleDB", con);
adapter.Fill(subjects);
con.Open();
DropDownList1.DataSource = subjects;
DropDownList1.DataTextField = "VehicleMake";
DropDownList1.DataValueField = "VehicleMake";
DropDownList1.DataBind();
if(!String.IsNullOrEmpty(Session["vehiclemake"] as string))
{
DropDownList1.SelectedIndex =
DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(Session["vehiclemake"].ToString()));
}
con.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string makename = DropDownList1.SelectedItem.Value;
keepname = makename;
Session["vehiclemake"] = keepname;
Response.Redirect("default.aspx?QSVehicleMake="+makename);
}
答案 1 :(得分:0)
How to implement cascading DropDownList ASP.Net control?
不要Response.Redirect()
SelectedIndexChanged()
中的同一页面
最好将DropDownList2
放在UpdatePanel
中以避免整页回发,这是DropDownList1
被清除的原因。
答案 2 :(得分:-1)
这可能是因为您的下拉列表在回发时再次绑定。尝试以下代码。
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//write your dropdownlist1 binding code here
}
}