Roi84
Roi84

Reputation: 99

C# Listbox sort items

Im new to programming and Im having a problem with a listbox. Im reading text from a file, and I want the last file in the file to be the first in the listbox. How to I do this?? This is a school project :)

This is the code I have so far:

if (File.Exists(file))
        {

            FileInfo fileInfo = new FileInfo("nema.csv");
            StreamReader read = fileInfo.OpenText();
            while (!read.EndOfStream)
            {
                listBox1.Items.Add(read.ReadLine());
            }

            read.Close();
        }

Upvotes: 0

Views: 1424

Answers (5)

Sam Casil
Sam Casil

Reputation: 948

Just use Listview either than listbox.

  1. Go to properties of ListView
  2. Click the SORTING
  3. Choose descending

Upvotes: 0

icaptan
icaptan

Reputation: 1535

I assume you to handle read textfile

While Reading TextFile store all string in a List Collection.

        List<string> listItems = new List<string>();
        FileStream fs = new FileStream(@"c:\YourFile.txt", FileMode.Open);
        StreamReader sr = new StreamReader(fs);

        string line = "";

        int lineNo = 0;
        do {
            line = sr.ReadLine();
            if (line != null) {
                listItems.Add(line);
            }
        } while (line != null);
        listItems.Sort();

        foreach(string s in listItems)
        {
              yourListBox.Items.Add(s);

        }

Upvotes: 0

Random Dev
Random Dev

Reputation: 52280

it's hard to tell without code but basically you have to use Insert(0,item) instead of Add(item) to reverse the order. The code coud look something like this:

using(var reader = System.IO.File.OpenText(pathOfFile))
{
   myListBox.Items.Insert(0, reader.ReadLine());
}

Upvotes: 4

meziantou
meziantou

Reputation: 21337

To add a new object at the first place of the listbox listbox.Items.Insert(0, objectToAdd)

Upvotes: 0

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

  • Read the contents of the file.
  • Put them in a list
  • Add the items that are in the list to the ListBox, but make sure you start from the last item in the list, and go to the first.

Upvotes: 0

Related Questions