Home > DeveloperSection > Forums > How to set a asp:DropDownList SelectedValue to a Session Variable?
Tom Cruser
Tom Cruser

Total Post:28

Points:196
Posted on    December-21-2014 10:28 PM

 ASP.Net C#  Session Variable  Dropdown 
Ratings:


 2 Reply(s)
 1403  View(s)
Rate this:

There are several articles describing how to do this is code behind however:

 

Is it possible to set the value of a dropdownlist to a session variable on the aspx page?

 

I am using SqlDataSource to populate the dropdownlist so do not wish to add code behind if it can be avoided.

 

<asp:DropDownList ID="ddl" runat="Server" DataSourceID="sqlDS" DataValueField="ID" DataTextField="TEXT" AppendDataBoundItems="true">

  <asp:ListItem Text="" Value="" Selected="True" />

</asp:DropDownList>

 

<asp:SqlDataSource ID="sqlDS" runat="Server" SelectCommand="spDS" SelectCommandType="StoredProcedure" />

Set Session("ID") as selected value on load?

 

The dropdown list is already populated from the sqldatasource. I just want to set the initial value on page load.



Pooja Malohtra
Pooja Malohtra

Total Post:47

Points:331
Posted on    December-22-2014 5:10 AM

You need a server side code in order to use Session. The following code doesn't requires code behind file, but again the code inside script will run at server side.

 

<asp:DropDownList ID="ddl" runat="Server"

   DataSourceID="sqlDS"

   DataValueField="ID"

   DataTextField="TEXT"

   AppendDataBoundItems="true"

   OnSelectedIndexChanged="ddl_SelectedIndexChanged"

   AutoPostBack="True">

  <asp:ListItem Text="" Value="" Selected="True" />

</asp:DropDownList>

 

<asp:SqlDataSource ID="sqlDS" runat="Server"

  SelectCommand="spDS" SelectCommandType="StoredProcedure" />

 

<script runat="server">

    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)

    {

        Session["SelecteValue"] = ddl.SelectedValue;

    }

</script>

Note: Make sure AutoPostBack="True" for DropDownList.


Goti Bandu

Total Post:119

Points:835
Posted on    December-22-2014 6:46 AM

you'll need an event for your dropdown list on change. Are you using C# or VB.net for your codebehind?

 

add to onSelectedIndexChanged="ddl_OnSelectedIndexChanged"

 

to your code behind add:

 

{this is C# vb is similar}

 

protected void ddl_OnSelectedIndexChanged(Object sender, EventArgs e)

{

    Session["selectedID"] = ddl.selectedValue;

}

to your page load, add

 

if (isPostback)

{

    ddl.selectedValue = Session["selectedID"];

}


Don't want to miss updates? Please click the below button!

Follow MindStick