C# Listbox sort items
Im new to programmin开发者_StackOverflowg 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();
}
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());
}
- 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.
To add a new object at the first place of the listbox listbox.Items.Insert(0, objectToAdd)
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);
}
Just use Listview either than listbox.
- Go to properties of ListView
- Click the SORTING
- Choose descending
精彩评论