简体   繁体   中英

session variables in an ASP.NET

hi guy i am trying to place my session in to a drop down, any help would be great. at the moment it puts the data in to a label, i wish to put it into a dropdown with it adding a new string every time i click button without getting rid of the last

default page

protected void Button1_Click1(object sender, EventArgs e)
{
    Session["Fruitname"] = TbxName.Text; // my session i have made
}

output page

protected void Page_Load(object sender, EventArgs e)
{
    var  fruitname =  Session["Fruitname"] as String; // my session ive made
    fruit.Text = fruitname; // session used in lable
}

Have Tried

           var myFruits = Session["Fruitname"] as List<string>;
        myFruits.Add(listbox1.Text);

but i get error when i try to run the program

Broken glass thanks for your help, it is still not doing what i need but its getting there.

 var fruitname = Session["Fruitname"] as String; // my session ive made
           fruit.Text = string.Join(",", fruitname); // session used in lable

this is what is working. i need a dropdown to display all the strings put into TbxName.Text; to output into fruit

Just use a List<string> instead of a string then.

 var myFruits = Session["Fruitname"] as List<string>;
 myFruits.Add(TbxName.Text);

Has been fixed using code found else where

button page code bellow

 protected void Button1_Click1(object sender, EventArgs e)
    {

       // Session["Fruitname"] = TbxName.Text; // my session i have made

        MyFruit = Session["Fruitname"] as List<string>;
        //Create new, if null
        if (MyFruit == null)
            MyFruit = new List<string>();

        MyFruit.Add(TbxName.Text);

        Session["Fruitname"] = MyFruit;
{
public List<string> MyFruit { get; set; }
}

page where display

 protected void Page_Load(object sender, EventArgs e)
    {


        MyFruit = Session["Fruitname"] as List<string>;
        //Create new, if null
        if (MyFruit == null)
            MyFruit = new List<string>();
        ListBox1.DataSource = MyFruit;
        ListBox1.DataBind();


    }

    public List<string> MyFruit { get; set; }
}

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