从文件加载列表框

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

阿巴斯给了你足够的答案,但是有一些问题,所以我想我会添加自己的答案。 问题:

  1. Streams(任何实现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(); 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 ); } } 

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

  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); } 

您需要做的就是为每个按钮创建一个事件处理程序。 您可以通过双击visual-studio设计器上的按钮来完成。 然后,您将看到具有以下新创建的代码窗口

 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. } 

希望它有所帮助,祝你好运!

试试这个例子,记得包括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(); } } 

问候。