[英]How to add contents of a file to listview C#
The file name is contacts.txt. 文件名是contacts.txt。 Its contents are:
其内容是:
line 1: Adam
line 2: adam@gmail.com
line 3: Kris
line 4: kris@gmail.com
I have a listview named listview1
. 我有一个名为
listview1
的列表listview1
。 It has 2 columns, ColumnHeader1
& ColumnHeader2
它有2列,
ColumnHeader1
和ColumnHeader2
I want to add the name in the file to ColumnHeader1
and email to ColumnHeader2
, ie, like: 我想将文件中的名称添加到
ColumnHeader1
并通过电子邮件发送到ColumnHeader2
,即:
Adam adam@gmail.com
Kris kris@gmail.com
How do I do that? 我怎么做?
Also, I want this to happen automatically every time the form is loaded. 另外,我希望每次加载表单时自动发生这种情况。
Thank You in advance. 先感谢您。
Tried this. 试过这个。
using (StreamReader sr = new StreamReader(@"C:\Contacts.txt"))
{
while (sr.EndOfStream)
{
ListViewItem lvi = new ListViewItem(sr.ReadLine());
lvi.SubItems.Add(sr.ReadLine());
listView1.Items.Add(lvi);
continue;
}
sr.Close();
}
Take the continue
word out. 把
continue
说出来。 It shouldn't be necessary. 没必要。
Try something like this: 尝试这样的事情:
using (StreamReader sr = new StreamReader(@"C:\Contacts.txt"))
{
while (-1 < sr.Peek())
{
try
{
string name = sr.ReadLine();
string email = sr.ReadLine();
var lvi = new ListViewItem(name);
lvi.SubItems.Add(email);
listView1.Items.Add(lvi);
} catch (Exception) { }
}
sr.Close();
}
That try/catch
is there just in case there are not an even number of entries in your file. 只要文件中没有偶数条目,就可以
try/catch
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.