Friday, November 19, 2010

How do I load ANY text file using a button into ListBox1 in the vb.net programming language?

This means, each line in the text file will be read in ListBox1 as each line. Example: I have a text file with entries:

andrea

bob

gordon

When I click on my button a dialog box pops up and allows me to load a text file. Once loaded itll load into the ListBox1 like:

andrea

bob

gordonHow do I load ANY text file using a button into ListBox1 in the vb.net programming language?
This should do it. It's a library routine so I made it public/static. However, if you just want to stick it in a form, you could easily make it private and lose both parameters in favor of specifying the list box and filename directly. (I like library routines, though!)



public static void PopulateListBoxFromFile( ListBox listbox, string filename )

{

// Clear anything already in the list box

listbox.Items.Clear();



// Use the using keyword to ensure that the stream

// reader will be disposed after use

using ( StreamReader reader = new StreamReader( filename ) )

{

string line;



// Read lines from the file until there are no more lines

while ( ( line = reader.ReadLine() ) != null )

{

listbox.Items.Add( line );

}

}

}

No comments:

Post a Comment