简体   繁体   中英

ASP.net save dropdown-list Selected-Item as a session

I want to save the selected item of a drop down list as a session but I am always getting the first result from the locations table.

ASP.net:

<div>
    <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
</div>

C# (just getting the locations to the drop down list is working fine)

using(SqlConnection con = new SqlConnection(CS))
{
    SqlCommand cmd = new SqlCommand("select location_id, location_name from locations", con);

    con.Open();
    DropDownList1.DataTextField = "location_name";
    DropDownList1.DataValueField = "location_id";
    DropDownList1.DataSource = cmd.ExecuteReader();
    DropDownList1.DataBind();
}

The problem: always retrieving the first location from the db.

protected void btnGo_Click(object sender, EventArgs e)
{
    string location;
    Session["userLocation"] = DropDownList1.SelectedItem;
    location = Session["userLocation"].ToString();
}

Thanks for the helpers.

You should do the binding only if Page.IsPostBack equals False .

The reason might be that your data operation for filling the DropDownList1 is called every time the page is requested. It is also possible that this data retrieval happens before btnGo_Click is executed and as a result the SelectedIndex will reset to 0 which is the first location in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM