How to keep DropDownList1 selected value after postback?
我有两个下拉列表。一旦选择了DropDownList1值,DropDownList2将基于DropDownList1进行填充。
但刷新页面后,DropDownList 1所选值将更改为最上面的值(DropDownList由数据库填充)。
ASPX:
1 | </asp:DropDownList> |
政务司司长:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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); } |
为此,可以使用会话值,使用此值可以从下拉列表中查找项
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | 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); } |
如何实现级联DropDownList ASP.NET控件?
不要把
这可能是因为您的下拉列表在回发时再次绑定。尝试下面的代码。
1 2 3 4 5 6 7 8 | protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { //write your dropdownlist1 binding code here } } |