【问题标题】:Loading a listbox from a file从文件加载列表框
【发布时间】:2012-03-31 03:21:17
【问题描述】:

这是我第一次创建 C# 程序,如果这个问题看起来很基础,我深表歉意。我的设计表单上有 3 个列表框和 3 个按钮,当我单击列表框的相应按钮时,我想将项目列表加载到每个文本框中。有人可以指导我如何做到这一点。

【问题讨论】:

  • 那么告诉我们吧。你自己走了多远,你在哪里卡住了?
  • 我刚拿起 Visual C# 2010,在书中找不到关于如何填充列表框的示例。这些介绍性书籍从不只展示基础知识。我需要提前取些东西

标签: c# winforms listbox


【解决方案1】:

Abbas 已经给了你一个足够的答案,但是它有几个问题,所以我想我会添加我自己的回应。问题:

  1. 流(任何实现IDisposable 的东西)在您完成后需要关闭。为此,您可以手动调用 Dispose() 或将对象的创建封装在 using 块中。
  2. 您不应该像那样将项目一个一个地添加到列表框中,以防有大量项目。这将导致性能不佳,并且列表框会在添加每个项目后更新/重绘时闪烁。

我会这样做:

using System.IO;
// other includes

public partial class MyForm : Form
{
    public MyForm()
    {
        // you can add the button event 
        // handler in the designer as well
        someButton.Click += someButton_Click;
    }

    private void someButton_Click( object sender, EventArgs e )
    {
        PopulateList( "some file path here" );
    }

    private void PopulateList( string filePath )
    {
        var items = new List<string>();
        using( var stream = File.OpenRead( filePath ) )  // open file
        using( var reader = new TextReader( stream ) )   // read the stream with TextReader
        {
            string line;

            // read until no more lines are present
            while( (line = reader.ReadLine()) != null )
            {
                items.Add( line );
            }
        }

        // add the ListBox items in a bulk update instead of one at a time.
        listBox.AddRange( items );
    }
}

【讨论】:

  • 关于阅读器的关闭:我没有把它放在那里,因为这只是一个小例子,但你对关闭阅读器的“使用”语句是正确的。而且我不知道一次读取文件的性能会更高,感谢您的解释! ;)
  • @Abbas:是的,我正要留下它作为评论,但决定只留下一个答案。我认为您忽略了它,因为它只是一个简单的示例,但由于 OP 是初学者,我认为最好也解释一下这部分。
  • 你解释得很好。另外,我也学到了一些新东西! :)
  • @Abbas:嗯,很高兴我能提供一些帮助;)。将项一个接一个地添加到 ListBox 的问题是控件在添加每个项后都会刷新。因此,对于相对大量的 Add() 顺序调用和过程中的 UI 闪烁,它最终会变得非常慢。作为一般规则,如果要添加的项目数量未知,最好使用 AddRange()。
【解决方案2】:

这些是在列表框中加载文本文件的步骤。

  1. 逐行读取文本文件
  2. 阅读时,填充列表框

这是一个关于如何做到这一点的小例子:

string line;
var file = new System.IO.StreamReader("C:\\PATH_TO_FILE\\test.txt");
while ((line = file.ReadLine()) != null)
{
    listBox1.Items.Add(line);
}

【讨论】:

    【解决方案3】:

    您需要做的就是为每个按钮创建一个事件处理程序。 您可以通过双击视觉工作室设计器上的按钮来完成。 然后你会看到下面新建的代码窗口

    private void button1_Click(object sender, EventArgs e)
    {
    
    }
    

    在此方法上,实现您的项目加载方法并将它们添加到您的 ListBox.Items。 例如:

    private void button1_Click(object sender, EventArgs e)
    {
    string[] allLines = File.ReadAllLines(@"C:\Test.txt"); // reads all lines from text file
    listBox1.AddRange(allLines); // Adds an array of objects into the ListBox's Item Collection.
    }
    

    希望对你有帮助,祝你好运!

    【讨论】:

      【解决方案4】:

      试试这个例子,记得包含 System.IO;

      使用 System.IO;

              private void button3_Click(object sender, EventArgs e)
          {
              //Pass the file path and file name to the StreamReader constructor
              StreamReader sr = new StreamReader("youfilePath");
              string line = string.Empty;
              try
              {
                  //Read the first line of text
                  line = sr.ReadLine();
                  //Continue to read until you reach end of file
                  while (line != null)
                  {
                      this.listBox1.Items.Add(line);
                      //Read the next line
                      line = sr.ReadLine();
                  }
      
                  //close the file
                  sr.Close();
              }
              catch (Exception e)
              {
                  MessageBox.Show(e.Message.ToString());
              }
              finally
              {
                  //close the file
                  sr.Close();
              }
          }
      

      问候。

      【讨论】:

        猜你喜欢
        • 2019-06-06
        • 2017-09-27
        • 2012-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-08
        • 2021-08-17
        相关资源
        最近更新 更多