简体   繁体   English

如何在一个会话中存储多个选定的列表框项目并在其他表单上查看?

[英]how to store multiple selected listbox items in a session and view on another form?

The thing I want to do is that i want to select 1,2 or 3 items from the listbox and save them into a session and then display them all on another form in a listbox. 我想做的是,我想从列表框中选择1,2或3个项目,并将它们保存到会话中,然后将它们全部显示在列表框中的另一个窗体上。

Here's my code! 这是我的代码! This is my first post on stack overflow, so no hate please <3 这是我关于堆栈溢出的第一篇文章,所以请不要讨厌<3

    //WebForm1

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            lstProducts.Items.Add("Soap");
            lstProducts.Items.Add("Schampoo");
            lstProducts.Items.Add("Conditioner");
        }
    }

    protected void cmdBuy_Click(object sender, EventArgs e)
    {
            string[] products = new string[3];

            for (int i = 0; i < lstProducts.Items.Count; ++i)
            {
                if (lstProducts.Items[i].Selected)
                    products[i] = lstProducts.Items[i].Text;
                else
                    products[i] = "0";
            }

            Session["Cart"] = products;

    }

    protected void cmdCart_Click(object sender, EventArgs e)
    {
        if (Session["Cart"] != null)
        {
            Response.Redirect("WebForm2.aspx");
        }
    }
}


    //WebForm2


    protected void Page_Load(object sender, EventArgs e)
    {
        string[] products = (string[])Session["Cart"];

        for (int i = 0; i < 3; ++i)
        {
            if (products[i] != "0")
            {
                lstCart.Items.Add(products[i]);
            }
        }
    }
}
}

The thing is that I only get the last selected item to display in the listbox on form2??? 事情是,我只得到最后选择的项目显示在form2的列表框中???

Try this 尝试这个

To store all items of the of the list box, you can add that items in array as: 要存储列表框的所有项目,您可以将这些项目添加为数组:

string[] a = new string[]{"item 1","item 2","item 3"};
Session["values"] = a;

And in the next page, you can retrieve it like this. 在下一页中,您可以像这样检索它。

string[] a = (string[])Session["values"]

EDIT #1 编辑#1

your case you can do like 你的情况,你可以喜欢

        ArrayList al = new ArrayList();
        for (int i = 0; i < ListBox1.Items.Count; i++)
        {
            if (ListBox1.Items[i].Selected == true)
            {
                al.Add(ListBox1.Items[i].Value);
            }
        }
        Session["selectedValues"] = al;

now you can use this sessiom variable in another page, but don't forget to cast in ArrayList type of object. 现在您可以在另一个页面中使用此sessiom变量​​,但不要忘记强制转换为ArrayList类型的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM