Click here to Skip to main content
15,908,013 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.
I am really stuck on a piece of code. I have nothing to show as all the code I’ve tried hasn’t worked.

I have a list box where the user can enter numbers ( many of little as they like)

I also have a button “make my number ascend”

When the user clicks the ascend button I need the list of numbers to pop up on a message box in an ascending view. Please can someone help me with this. I’m really struggling.

What I have tried:

I have tried many different codes but no of it works I just get error messages
Posted
Updated 17-Feb-18 19:16pm
Comments
Patrice T 17-Feb-18 19:08pm    
Come back when you have some code to show.
BillWoodruff 18-Feb-18 0:10am    
No code, no help.

1 solution

You haven't provided much for anyone to help but I'm willing to bet the likely issue is that your listbox is treating your numbers as strings so once you start getting into stuff > 9, your order by gets funky (Ex: 1, 10, 2,3,4,5,6,7,8, 9).

Because i'm lazy and don't feel like putting this into visual studio this code snippet may be buggy, but part of learning is figuring things out for yourself...so if it doesn't compile/run...google is your friend.

C#
var listbox = new ListBox();
listbox.Items.Add("1");
listbox.Items.Add("2");
listbox.Items.Add("3");
listbox.Items.Add("4");
listbox.Items.Add("5");
listbox.Items.Add("6");
listbox.Items.Add("7");
listbox.Items.Add("8");
listbox.Items.Add("9");
listbox.Items.Add("10");
listbox.Items.Add("11");
listbox.Items.Add("12");

// Option One - Note...may not compile

var orderedItemsOption1 = listbox.Items.Select(m=> Convert.ToInt32(m)).OrderBy(m=> m);

var listBoxToIntItems = new List<int>();

foreach(var item in listbox.Items)
{
   listBoxIoIntItems.Add(Convert.ToInt32(item));
}

var orderedItemsOption2 = listBoxToIntItems.Orderby(m=>m);


Those are 2 options of propbably quite a few for you to convert your listbox of items into an integer and have the order by function properly.

You need to look into Convert.ToInt32 and decide what method of converting strings to integers works best for you...Convert.ToInt32 will explode if you try and pass in say..."A" to it.
 
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