Charindu Edirisuriya Charindu Edirisuriya - 4 months ago 22
SQL Question

How to keep DropDownList1 selected value after postback?

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

But after the Page refresh's dropdownlist1 selected value is changed to the top most value.

(DropDownList is populate by a Databases)



CssClass="makeselect"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True" AppendDataBoundItems="true">
</asp:DropDownList>


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



}

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