I have typed numbers in a textbox and added them into a listBox. Now I need to order that listbox. This is my try:
int[] array = listBox1.Items.Cast<int>().ToArray<int>();
Array.Sort(array);
listBox1.Items.Clear();
foreach (int item in array)
{
listBox1.Items.Add(item);
}
It throws an 'System.InvalidCastException'. But I can't figure it out HOW to solve it.
This is as simple as
listBox1.Sorted = true;
UPDATE
var array = new object[listBox1.Items.Count];
listBox1.Items.CopyTo(array, 0);
listBox1.Items.Clear();
var sortedArray = array.Select(n => (object)Convert.ToInt32(n)).OrderBy(n => n).ToArray();
listBox1.Items.AddRange(sortedArray);
You can use a lambda
var array = listBox1.Items.OfType<string>().Select(x => int.Parse(x))
.ToArray();
First, I want to say that it is not a good idea to store data inside a control. Always put your data inside types that can handle them like a List, Dictionary, etc. and then bind that to your listbox object. I guess you are working on windows forms. Then add a property to your form and put all your data in it.
something like this
public partial class Form1 : Form
{
List<string> _items = new List<string>(); // <-- Add this
public Form1()
{
InitializeComponent();
_items.Add("One"); // <-- Add these
_items.Add("Two");
_items.Add("Three");
listBox1.DataSource = _items;
}
public void add()
{
_items.Add("four");
_items.Sort();
}
}
ListBox items can cast to string. So, You must cast it to string[], then convert to int[], then sort it and finally add sorted data to ListBox.
string[] strArray = listBox1.Items.Cast<string>().ToArray();
int[] intArray = strArray.Select(x => int.Parse(x)).ToArray();
Array.Sort(intArray);
listBox1.Items.Clear();
foreach (int item in intArray)
{
listBox1.Items.Add(item);
}
I hope this will be useful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.