Mike 19
Mike 19

Reputation: 15

How to group ListBox (Windows Forms)

I’m attempting to group the names in listbox1. Each item in listbox1 are seperated by a comma. I would like to attach the items to the previous one in the same line. Also the names (listbox 1) should be displayed in listBox2 only once in each line. The result should look as shown below (lb2). How can this be achieved? Thanks for your help!

´´´

listBox1.Items.Add(item.S1 + " , " + item.S2);

´´´

enter image description here

Upvotes: 0

Views: 421

Answers (1)

Francois
Francois

Reputation: 16

Made a quick app for you. Probably not the most efficient but gets the job done. Also added sorting to make it easier

 private void button1_Click(object sender, EventArgs e)
 {
     listBox2.Items.Clear();

     ArrayList namelist = new ArrayList();
     foreach (object o in listBox1.Items)
     {
         namelist.Add(o);
     }

     namelist.Sort();
     string newItem = "";
     for (int i = 0; i < namelist.Count; i++)
     {
         string item = namelist[i].ToString();

         string firstName = item.Substring(0, item.IndexOf(','));
         string initials = item.Substring(item.IndexOf(',')+1);
         initials = initials.Trim();

         //newItem +=  initials;

         if (i + 1 < namelist.Count)
         {
             string nextItem = namelist[i+1].ToString();
             string nextFirstName = nextItem.Substring(0, nextItem.IndexOf(','));
             string nextInitials = nextItem.Substring(nextItem.IndexOf(',') + 1);

             if(firstName.ToLower() == nextFirstName.ToLower())
             {
                 newItem += ", " + initials;
             }
             else
             {
                 newItem = firstName + newItem + ", " + initials;
                 listBox2.Items.Add(newItem);
                 newItem = "";
             }
         }
         else
         {
             newItem = firstName + newItem + ", " + initials;
             listBox2.Items.Add(newItem);
             newItem = "";
         }
     }
 }

Results of code

Upvotes: 0

Related Questions