Skip to content
Advertisement

How to keep DropDownList1 selected value after postback?

I have two DropDownLists. Once a DropDownList1 value is selected, DropDownList2 will populate based on Dropdownlist1.

But after the page refreshes, the dropdownlist1 selected value is changed to the top-most value (the DropDownList is populate by a database).

.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);
}

Advertisement

Answer

You can use SESSION value for this purpose, using this value you need to find Item from dropdown

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);
     }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement