Question

I'm trying to set the selected value of a DropDownList on Page_Load using a value that is saved into a Session variable. The DropDownList is already populated and the value is stored along with other info in a session. I'm creating an edit entry page and want to have all of the fields already populated with the info from the Session.

What I've done is populate TextBox with the Session Variables, but for the Advisors section I need the User to enter a number instead of a name. So I need to use a DropDownList to make sure that information is entered accurately. I've looked into methods of databinding, databound, using a data source, etc but it seemed like all of those DropDownLists were generated dynamically. Any help would be much appreciated.

My .aspx Code:

<asp:TextBox runat="server" ID="fname" MaxLength="100"></asp:TextBox>

<asp:DropDownList ID="advisors" runat="server">
                <asp:ListItem Value="">Select Advisor</asp:ListItem>
                <asp:ListItem Value="2">Joe Schmo</asp:ListItem>
</asp:DropDownList>

Code Behind:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                fname.Text = Session["fname"].ToString();
                lname.Text = Session["lname"].ToString();
                sex.Text = Session["sex"].ToString();
                sid.Text = Session["sid"].ToString();
                email.Text = Session["email"].ToString();
                phone.Text = Session["phone"].ToString();
                advisors.SelectedValue = Session["advisor"].ToString();
            }

        }

UPDATE:

So I'm dumb. The Session variable was storing the name "Joe Schmo" not the Value "2". The below code worked for me.

foreach (ListItem listItem in advisors.Items)
{
   listItem.Selected = listItem.Text.Equals(Session["advisor"].ToString());
}
Was it helpful?

Solution

try this

foreach (ListItem listItem in advisors.Items)
{
      if(listItem.Text.Equals(Session["advisor"].ToString())

 DropDownList1.Items.FindByValue(Session["advisor"].ToString()).Selected = true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top