Open In App

How to sort elements in the ListBox in C#?

In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you are allowed to sort the elements present in the ListBox using Sorted Property of the ListBox. This property always sorts the string type elements in the alphabetical order and integer type elements in ascending order. The default value of this property is false. You can set this property in two different ways:

1. Design-Time: It is the easiest way to sort the elements present in the ListBox as shown in the following steps:



2. Run-Time: It is a little bit trickier than the above method. In this method, you can sort the elements present in the ListBox control programmatically with the help of given syntax:



public bool Sorted { get; set; }

Here, the value of this property is of System.Boolean type. If you want to sort the elements present in the Listbox, then set the value of this property to true. Otherwise, false. The following steps show how to set the Sorted property of the ListBox dynamically:


Article Tags :
C#