Loading a listbox from a file

2019-05-29 15:15发布

问题:

This is my first time creating a C# program so I apologize if this question seems basic. 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. can someone instruct me on how to do this.

回答1:

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. You can do this by manually calling Dispose() or by wrapping the creation of the object in a using block.
  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 );
    }
}


回答2:

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


回答3:

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



回答4:

try this example , remember to include System.IO;

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