user1375948
user1375948

Reputation: 177

Sort combobox contents accortding to numbers

i have a combo box and i populate it with numbers from 1 to 40 but it shows them as 1 than 10-19 than 2 than 20-29 and so on even i tried to insert data trough code

for(int i=0;i<41;i++)
Combobox.Items.Inert(i,(i+1).ToString())

Also tried above code without conversion to string but Again it shows same result i think it brings them in ascending order but this is not what i want Kindly Tell me how to do it so that it displays numbers in order from 1-40 Thanks

Upvotes: 1

Views: 8315

Answers (6)

Tomasz
Tomasz

Reputation: 1

ComboBox always adds and sorts objects you add by their ".ToString()" function.

What you could always do is add an empty string prior to the numbers:

if(i < 10){ (Combo.Items.Add(i.ToString(StringFormat(" i",i)))); }
else { Combo.Items.Add(i); }

Then when you retrieve it, parse it as an int. (Not as stable as it should be, but a good start).

Upvotes: 0

Vaughan Hilts
Vaughan Hilts

Reputation: 2879

You could always encapsulate it.

public class Item : IComparer
{
public Item(int value) { this.Value = value; }

   public int Value { get; set; }

       public int CompareTo(Item item)
  {
                 int ret = -1;
        if (Value < item.Value)
            ret = -1;
        else if (Value > item.Value)
            ret = 1;
        else if (Value == item.Value)
            ret = 0;
        return ret;
      }

}

Then simply...

for(int i = 0; i < 40; i++)
  comboBox.Items.Add(new Item(i));

Upvotes: 0

perilbrain
perilbrain

Reputation: 8197

try:-

for(int i=0;i<40;i++)
combobox.Items.Add((i+1).ToString("D2"));

Upvotes: -1

Ali Vojdanian
Ali Vojdanian

Reputation: 2111

Try this :

for(int i=0;i<41;i++)
Combobox.Items.Add(i);

Upvotes: -1

Josh
Josh

Reputation: 44906

Sorting of a ComboBox is always done Alphabetically and Ascending.

If you don't want this behavior, then you can simply turn it off by setting the Sorted property to false.

Upvotes: 0

Justin Pihony
Justin Pihony

Reputation: 67075

I believe this question is what you are looking for. You are going to have to do your own sorting and turn off the custom it seems.

From the article, here is the reflector code of the combobox sort (that is private):

public int Compare(object item1, object item2)  
{  
    if (item1 == null)  
    {  
        if (item2 == null)  
        {  
            return 0;  
        }  
        return -1;  
    }  
    if (item2 == null)  
    {  
        return 1;  
    }  
    string itemText = this.comboBox.GetItemText(item1);  
    string str2 = this.comboBox.GetItemText(item2);  
    return Application.CurrentCulture.CompareInfo.Compare(itemText, str2, CompareOptions.StringSort);  
} 

So, it converts everything to string, thus why turning off sort is your best option.

Upvotes: 3

Related Questions