在C# WinForm开发中,如果需要将本地的txt文件内容通过listView控件展示,可以按照以下步骤进行操作。
首先,定义文件路径和读取文件内容的集合。
string path = @"D:\test.txt";
List txtContent = new List();
使用文件流读取txt文件内容,并将其存储到集合中。
using (Stream stream = System.IO.File.OpenRead(path)) {
using (StreamReader reader = new StreamReader(stream, Encoding.Default)) {
string line = string.Empty;
while ((line = reader.ReadLine()) != null) {
txtContent.Add(line);
}
}
}
确保文件中的时间和信息之间有明显的分隔符,例如&,这有助于后续处理。
建议文件内容如下:
2011-10-10 12:00:00&我要吃饭
2011-10-11 12:00:00&我要减肥
在listView控件中添加列,并设置视图模式为Details。
this.listView1.Columns.Add("时间");
this.listView1.Columns.Add("信息");
this.listView1.View = View.Details;
遍历txtContent集合,将内容以&分隔,并绑定到listView。
foreach (string str in txtContent) {
string[] values = str.Split('&');
this.ListView1.Items.Add(new ListViewItem(new string[] { values[0], values[1] }));
}
完成以上步骤后,txt文件内容将会以时间-信息的形式展示在listView控件中。
温馨提示:答案为网友推荐,仅供参考