[英]How to get a Listbox to read to a Listbox
I am trying to open any selected textfile and have the text input be sent to a listbox... Originally I wrote this code for a textbox which worked great now that I am converting it to a listbox it doesnt seem to work so much. 我正在尝试打开任何选定的文本文件,并将输入的文本发送到列表框...最初,我为一个文本框编写了此代码,该代码现在非常有用,因为我将其转换为列表框,它似乎没有太大作用。 I left the default item names in order for better understanding of what is going on.
我保留了默认的项目名称,以便更好地了解发生了什么。
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label1.Text = openFileDialog1.FileName;
listBox1.Items.Add = File.ReadAllText(label1.Text);
}
}
尝试这个 :
listBox1.Items.AddRange(File.ReadLines(label1.Text).ToArray());
listBox1.Items.AddRange(File.ReadAllLines(label1.Text));
.Add()
is a method and you are treating it like a property. .Add()
是一种方法,您将其.Add()
属性。
Try this code instead: 请尝试以下代码:
listBox1.Items.Add(File.ReadAllText(label1.text));
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label1.Text = openFileDialog1.FileName;
//till here the same
//open filestream
System.IO.StreamReader file = new System.IO.StreamReader(openFileDialog1.FileName);
//loop trough lines
while ((line = file.ReadLine()) != null)
{
//add line to listbox
listBox1.Items.Add ( line);
}
}
}
string[] lines = File.ReadLines("SomeFile.txt").ToArray();
foreach (var line in lines)
{
listBox1.Items.Add(line);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.