In: Computer Science
The items in a listbox is treated as string. If we set the listbox Sorted property to True, the listbox will be sorted based on items' string value. A listbox with items 2 and 10, the sorted output will be 10, 2 which is not numeric ascending sequence.
If a listbox has only numbers, what would you do to display those items base on their numeric value in ascending order in the listbox?
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication42
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listBox1.Items.Add("3140");
listBox1.Items.Add("109");
listBox1.Items.Add("2");
listBox1.Items.Add("10");
listBox1.Items.Add("180");
}
private void button1_Click(object sender, EventArgs e)
{
List
foreach (var o in listBox1.Items)
{
list.Add(Convert.ToInt16(o));
}
list.Sort();
listBox1.Items.Clear();
foreach (var o in list)
{
listBox1.Items.Add(o);
}
}
}
}