nitha raj
nitha raj

Reputation: 139

how to display checkbox selected items in ascending order

This is my code:

protected void check1_SelectedIndexChanged(object sender, EventArgs e)       
{            
    for (int i = 0; i < check1.Items.Count; i++)           
    {               
        if (check1.Items[i].Selected)
        {
            comment.Text = "\u2022 "+check1.Items[i].Text  +"<br/>"+ comment.Text;
        }
    }
}

For example if i have checkbox list:

*apple *Mango *Orange *Grapes

and i have selected apple, orange and grapes it is displaying as

grapes orange apple

I want it to be displayed as:

apple orange grapes

Upvotes: 0

Views: 2085

Answers (2)

Waqar Janjua
Waqar Janjua

Reputation: 6123

First store these items in a List then sort it and then set it to Coment.Text property

protected void check1_SelectedIndexChanged(object sender, EventArgs e) 
{

 List<string> lst = new List<string>();

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

    if (check1.Items[i].Selected)
    {           
       lst.Add(check1.Items[i]);            
     }           
  }

  lst.Sort();
  foreach(list l in lst)
  {
     comment.Text += l;
  }
 }

Upvotes: 0

HatSoft
HatSoft

Reputation: 11201

You can sort it using Linq and make use of it

Example :

var sortedCheckBoxes = check1.Items.Where(c => c.Selected).OrderBy(c => c.Text);

Upvotes: 1

Related Questions