简体   繁体   中英

Return array values into listbox (C#)

I have an array that gets its values from a text file. Each line is an array value. I am trying to make each of those array values go into the listbox. Such as

[0] - Hello
[1] - Goodbye

and in the listbox, the first option will be hello, and the second will be goodbye etc.

The text file is Hello and Goodbye on seperated lines

Heres my code to sort the array from the text file:

StreamReader sr = new StreamReader("text.txt");
int counter = 0;
string line;
string[] linea;
linea = new string[100];
while ((line = sr.ReadLine()) != null)
{
    linea[counter] = line;
    counter++;
}
sr.Close();

And here's my code for the list box:

this.listBox1.Items.AddRange(new object[] {
// Values go here
// i want the arrays here, so that its like "hello", "goodbye",
});

Help is much appreciated. I am using MS Visual Studio 2010.

You can assign DataSource for Listbox:

this.listBox1.DataSource = object[];

HTH.

I haven't tested it yet but I think you can just do:

this.listBox1.Items.AddRange(linea);

Edit:

Just tested it and it works great! :)

Edit: just realized that it doesn't need a cast

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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