Preserve checkboxlist using session

Been working on this for 4 hours now!

1. I have a checkboxList on page xyz.aspx
2. There's a seach link on this page. User clicks it, goes to search.aspx. Selects a row. I pass the id to xyz.aspx page
3. I use this ID and call the database, get a value and bind to checkboxList. So far so good.
4. But now, user might leave this page again and go to search and get another id. Now, I have 2 ids.
5. When I get back to page xyz.aspx, I want to bind both Ids to the checkboxlist. I'm thinking about using a session var and loop thru the session and bind bit not sure how to do this.

This is my code:

 if (Session["providerId"] != null)

            List<usp_LoadProviderNameResult> provider = sd.LoadProvider(ReferredToProviderId);

            ckProviders.DataSource = provider;
            ckProviders.DataTextField = "Providername";
            ckProviders.DataValueField = "Id";
        List<string> selectedProviders = new List<string>();
        Session["providerId"] = selectedProviders;

Open in new window

Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

dhawalsethConnect With a Mentor Commented:
Hi Farzadw,

You are pretty near to what you want to achieve. I believe the code you wrote is a complicated one and you can replace it with string[] object with ',' or ';' as delimiter to separate two entries.
There are a few things which i would like to point out.
1. By step 3 you mean that you pick a value from the database based on the passed id, and then select the value in checkboxlist.(correct me if i am wrong)
2. The list<string> object works fine, but if there is an existing entry in your check box list- it will not be preserved.
Possible solution: do this functionality when you are navigating to new page (using a button click event will do)
List<string> selectedProviders = new List<string>();
replace this line with:
if(ckProviders.Items.Count > 0)
for(int var =0; var > ckProviders.Items.Count; var++)
selectedProviders.Add(value you want to add);
  Session["providerId"] = selectedProviders;
On page load do a reverse after you have bind your checkbox list.
if(Session["providerId"] != null)
List<string> selectedProviders = Session["providerId"];//Please convert this value back to List<string> type.
            foreach (string providerId in selectedProviders)
                ListItem item = ckProviders.Items.FindByValue(providerId);
                if (item != null)
                    item.Selected = true;

If you want to play with an string[] object follow the link shared above, works like a charm and a very good example is posted.

Mark as answer if helped. You might need to fix here and there if required in the code.
CamilliaAuthor Commented:
let me review, thanks
All Courses

From novice to tech pro — start learning today.