Florence Blogspot about asp.net tutorials and web design and web development

Monday, May 25, 2009

C# How to place an arraylist inside a Session Variable and Iterate through it

Question:

Hi,

In my web form, I want to store multiple IDs inside an arraylist and then store the arraylist in a Session Variable (e.g. Session["InstallationID"]) to use it in a different web form where I want to use every ID inside the arraylist.

How do I place the arraylist inside the Session Variable and then take each ID off of it to be used in a SELECT statement?

Answer:


Something like this:

1    protected void Page_Load(object sender, EventArgs e)
2 {
3 if (!IsPostBack)
4 {
5 List<int> ids = new List<int> {1, 2, 3, 4, 5};
6 Session["myIds"] = ids;
7 }
8 }
9
10 protected void buttonSubmit_Click(object sender, EventArgs e)
11 {
12 List<int> ids = Session["myIds"] != null ? (List<int>) Session["myIds"] : null;
13 if (ids != null)
14 {
15 foreach (int id in ids)
16 {
17 ListBox1.Items.Add(String.Format("select * from customer where id={0}", id));
18 }
19 }
20 }

OR


protected void Page_Load(object sender, EventArgs e)
{
//Save
ArrayList idList = new ArrayList();
idList.Add("1");
idList.Add("2");
idList.Add("3");
Session["InstallationId"] = idList;
}//Page2

protected void Page_Load(object sender, EventArgs e)

{

//Retreive

ArrayList idList = (ArrayList)Session["InstallationId"];

string id1 = idList[0].ToString() ;

string id2 = idList[1].ToString();

string id3 = idList[2].ToString();

}

Refer for references: http://forums.asp.net/t/1425975.aspx



No comments:

Search