简体   繁体   English

从文件加载列表框

[英]Loading a listbox from a file

This is my first time creating a C# program so I apologize if this question seems basic. 这是我第一次创建C#程序,因此对于这个问题似乎很基本,我深表歉意。 I have 3 list boxes on my design form along with 3 buttons I'd like to load a list of item into each text box when I click the corresponding button for the listbox. 我在设计表单上有3个列表框以及3个按钮,当我单击列表框的相应按钮时,我希望将项目列表加载到每个文本框中。 can someone instruct me on how to do this. 有人可以指导我如何执行此操作。

Abbas has given you a sufficient answer, but there are a couple of problems with it, so I thought I would add my own response. 阿巴斯给了您足够的答案,但是它有很多问题,所以我想我会添加自己的回答。 The issues: 问题:

  1. Streams (anything that implements IDisposable ) need to be closed after you're done with them. 在完成流之后,需要关闭流(任何实现IDisposable )。 You can do this by manually calling Dispose() or by wrapping the creation of the object in a using block. 您可以通过手动调用Dispose()或将对象的创建包装在using块中来实现。
  2. You shouldn't add items to the list box one by one like that in case there are a large number of items. 如果有大量项目,则不应将项目一一添加到列表框中。 This will cause poor performance and the list box will flicker as it updates/redraws after each item is added. 这将导致性能下降,并且在添加每个项目后更新/重绘列表框时会闪烁。

I would do something like this: 我会做这样的事情:

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

These are the steps to load the textfile in the listbox. 这些是在列表框中加载文本文件的步骤。

  1. Read textfile line by line 逐行读取文本文件
  2. While reading, populate the listbox 阅读时,填充列表框

Here's a small example on how to do this: 这是一个有关如何执行此操作的小示例:

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

all you need to do is create an event handler for each button. 您需要做的就是为每个按钮创建一个事件处理程序。 You can do it by double-clicking the button on the visual-studio designer. 您可以通过双击Visual Studio设计器上的按钮来完成此操作。 Then you'll see the code window with the following new-created 然后,您将看到包含以下新创建的代码窗口

private void button1_Click(object sender, EventArgs e)
{

}

on this method, implement your item loading method and add them to your ListBox.Items. 在此方法上,实现您的项目加载方法,并将其添加到ListBox.Items。 for example: 例如:

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

Hope it helps and good luck! 希望对您有帮助,祝您好运!

try this example , remember to include System.IO; 试试这个例子,记得包括System.IO;

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

Regards. 问候。

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

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