0

I want to store all listbox control values in a string with "," separated so that I can show it in the label. I'm using for loop but giving error

 for (int i = 0; i < ListBox2.Items.Count; i++){

        if (ListBox2.Items[i].Selected == true || ListBox2.Items.Count > 0){
            string projectnames += ListBox2.Items[i].ToString();
        }
  }
4
  • 2
    What is the error exactly? Commented Apr 16, 2015 at 9:56
  • 1
    Why do you check || ListBox2.Items.Count > 0? That doesn't make much of a sense, does it? Commented Apr 16, 2015 at 9:59
  • ii just want to add items from left list box to right list box. if i will not give that condition , i have to select right box items while ubmiting otherwise it wil nt take Commented Apr 16, 2015 at 10:03
  • i think u r right both are no not necessary, one condition is enough i.e ListBox2.Items.Count > 0 Commented Apr 16, 2015 at 10:14

5 Answers 5

3
string projectnames = "";
bool firstValue = true;

for (int i = 0; i < ListBox2.Items.Count; i++)
            {

                if (ListBox2.Items[i].Selected == true || ListBox2.Items.Count > 0)
                {
                   if(!firstValue)
                   {
                      projectnames += ", " + ListBox2.Items[i].ToString();
                   }
                   else
                   {
                      projectnames += ListBox2.Items[i].ToString();
                      firstValue = false;
                   }

                }

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

Comments

0

Instead of the loop i'd use LINQ + String.Join:

var selected = ListBox2.Items.Cast<ListItem>()
    .Where(li => li.Selected)
    .Select(li => li.ToString());
string projectnames = String.Join(",", selected);

On that way it's much better to read and you don't need to care about trailing commas.

Comments

0

This will generate a string of all selected items in the list.

string projectnames = "";
for (int i = 0; i < ListBox2.Items.Count; i++)
{

    if (ListBox2.Items[i].Selected)
    {
       projectnames += ListBox2.Items[i].ToString() + ", ";
    }

 }

Comments

0

The most succinct method I can think of is:

var label = string.Join(",", listBox2.Items.Cast<string>());

(This uses System.Linq)

Comments

0

Try this, will help you!

protected void btnSave_Click(object sender, EventArgs e)
    {
        string selectedItem=string.Empty;
        if (ListBox1.Items.Count > 0)
        {
            for (int i = 0; i < ListBox1.Items.Count; i++)
            {
                if (ListBox1.Items[i].Selected)
                {
                    selectedItem += ListBox1.Items[i].Text.ToString() + ", ";
                    //insert command
                }
            }
        }
    }

Comments

Your Answer

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