简体   繁体   English

C#列表框排序项

[英]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());
}
  • 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. 将列表中的项目添加到ListBox,但请确保从列表中的最后一项开始,然后转到第一个。

在列表框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。

  1. Go to properties of ListView 转到ListView的属性
  2. Click the SORTING 点击排序
  3. Choose descending 选择降序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM