Gilad Adar
Gilad Adar

Reputation: 167

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.

Upvotes: 1

Views: 1698

Answers (1)

user3794166
user3794166

Reputation:

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.

Upvotes: 2

Related Questions