Domanda

I am trying to store the selected value of an item in my drop down list into a session variable after selecting it and pressing a button to add it to a session variable. My question is, is there a way to store multiple selections into different session variable with the same drop down list. Each session variable has the same value and I am unsure how to save each selected value into a new session variable.

protected void DropDownListAddNumber_SelectedIndexChanged(object sender, EventArgs e)
{
    Session["selectionOne"] = DropDownListAddNumber.Items.FindByValue(DropDownListAddNumber.SelectedValue);
    Session["selectionTwo"] = DropDownListAddNumber.Items.FindByValue(DropDownListAddNumber.SelectedValue);
    Session["selectionThree"] = DropDownListAddNumber.Items.FindByValue(DropDownListAddNumber.SelectedValue);
    Session["selectionFour"] = DropDownListAddNumber.Items.FindByValue(DropDownListAddNumber.SelectedValue);
}
È stato utile?

Soluzione

If multi-select is not your question, storing it by each variable will not scale well. If you want to store each selection into the Session, you can store a List of strings into the session. (taking advantage of the fact that the items are stored in the order we insert them in a list)

protected void DropDownListAddNumber_SelectedIndexChanged(object sender, EventArgs e)
{
 List<string> sessionList = GetSessionVariable();
 sessionList.Add(DropDownListAddNumber.Items.FindByValue
                 (DropDownListAddNumber.SelectedValue));
}

// you can access the selected values from the list
// if sessionList.Any(), then sessionList.Last() will contain 
// the last selected value.. etc.

private List<string> GetSessionVariable()
{
 var list = Session["SelectionValuesList"] as List<string>;

 if (list == null)
 {
  list = new List<string>();
  Session["SelectionValuesList"] = list;
 } 

 return list;
}

OR

if you still want to use multiple session variables, you need to do some sort of counter. multiple variables will be created. this is error prone.

int lastCounter = 0;

protected void DropDownListAddNumber_SelectedIndexChanged(object sender, EventArgs e)
{
    ++lastCounter;
    Session["selection" + lastCounter] = DropDownListAddNumber.Items
                                        .FindByValue(DropDownListAddNumber.SelectedValue);
}

// you can access last value as
// var lastSelectedValue = Session["selection" + lastCounter];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top