[英]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();
}
it's hard to tell without code but basically you have to use Insert(0,item)
instead of Add(item)
to reverse the order. 没有代码很难说,但是基本上您必须使用Insert(0,item)
而不是Add(item)
来颠倒顺序。 The code coud look something like this: 代码代码看起来像这样:
using(var reader = System.IO.File.OpenText(pathOfFile))
{
myListBox.Items.Insert(0, reader.ReadLine());
}
在列表框listbox.Items.Insert(0,objectToAdd)的第一位置添加新对象
I assume you to handle read textfile 我假设你要处理读取的文本文件
While Reading TextFile store all string in a List Collection. 在读取TextFile时,将所有字符串存储在List集合中。
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. 只需使用Listview而不是listbox。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.