Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi guys,

i really stuck on this for 4hours.this is my code:listbox that has name of staff
C#
foreach (ListItem item in ListBox1.Items)
{

    if (item.Selected)
    {

                com2.Parameters["@ListBox1"].Value += item.Text + ",";
     }
            //else
                //com2.Parameters["@ListBox1"].Value += item.Text + " ";
}

i want it store if item.selected more than 1 item then store with comma.else if only 1 item had selected then no comma. currently my data display comma even i select 1 item.i dont need the comma after name (eg: michael,) if 2 items (eg:michael,daniel,) i dont want like this
Posted
Updated 19-Jul-12 20:47pm
v2

C#
Boolean IsFirst=True;
foreach (ListItem item in ListBox1.Items)
{
 
    if (item.Selected)
    {
            if (IsFirst)
              {
                com2.Parameters["@ListBox1"].Value = item.Text;
                IsFirst=False;
              }
            else
              {
                com2.Parameters["@ListBox1"].Value +=","+ item.Text;
              }
     }
}

Hopefully It is your perfect solution
 
Share this answer
 
v2
Comments
musiw 21-Jul-12 5:00am    
thanx kaushik.
C#
string strSelected = string.Empty;
foreach (ListItem item in ListBox1.Items)
{
    if (item.Selected)
    {
           if(strselected == string.empty)
              strselected = item.text
           else
              strSelected += "," + item.Text 
    }
   
}
 
Share this answer
 
Hi,

Please use following code for trimming comma:
C#
string strSelected = string.Empty;
foreach (ListItem item in ListBox1.Items)
{ 
    if (item.Selected)
    { 
        strSelected += item.Text + ",";
    }
    strSelected = strSelected.TrimEnd(',');
    
}
com2.Parameters["@ListBox1"].Value = strSelected;
 
Share this answer
 
string str="";
foreach (ListItem item in ListBox1.Items)
{

if (item.Selected)
{
str+=(string.IsNullOrEmpty(str.trim())?item.text:","+item.text;
}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900