1

I'm trying to get checkbox list values to a single string. in ASP.net using C#.

Here's my code.. I have declared this globally.

   string hobbies = "";

This is the code to get the selected items to a string.

   protected void chkListHobbies_SelectedIndexChanged(object sender, EventArgs e)
   {
      for (int i=0;i<chkListHobbies.Items.Count;i++)
      {
         if (chkListHobbies.Items[i].Selected)
         {                
            hobbies += chkListHobbies.Items[i].Value + ",";
          }

    }
   hobbies = hobbies.TrimEnd(',');

I'm displaying this on button click

     protected void btnEnter_Click(object sender, EventArgs e)
     {
      Response.Write("Hobbies= "+hobbies);
     }

It doesn't give the expected output. Would like to get this corrected if it's wrong or would like to know how to do it properly. Thanks in advance.

1 Answer 1

1

You have to create hobbies list in your btnEnter_Click event handler because Asp.net webforms in stateless and you'll get a new hobbies variable after each postback. To address this issue you have to save hobbies state somehow (using viewstate or a hidden field) and use it later or as I suggested create hobbies list in btnEnter_Click.

Edit (examples):

1.Do the whole thing in btnEnter_Click:

protected void btnEnter_Click(object sender, EventArgs e)
   {
      string hobbies = "";
      for (int i=0;i<chkListHobbies.Items.Count;i++)
      {
         if (chkListHobbies.Items[i].Selected)
         {                
            hobbies += chkListHobbies.Items[i].Value + ",";
          }

    }
   hobbies = hobbies.TrimEnd(',');
   Response.Write("Hobbies=" + hobbies);

2.Use ViewState:

private string hobbies
{
   get { return (ViewState["hobbies"] ?? "").ToString(); }
   set { ViewState["hobbies"] = value; }
}

and the rest of your code is exactly the same.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.