需求:将文件中的电视节目单信息展示到列表中
步骤一:搭建电视节目单实体类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TVListProgram
{
/// <summary>
/// 电视节目单实体类
/// </summary>
public class TVList
{
/// <summary>
/// 电视节目时间
/// </summary>
public string TVTime { get; set; }
/// <summary>
/// 电视节目频道
/// </summary>
public string Channel { get; set; }
/// <summary>
/// 电视节目名称
/// </summary>
public string TVName { get; set; }
}
}
步骤二:搭建数据操作类。注意数据操作类的命名一般是在实体类后面加上Service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace TVListProgram
{
/// <summary>
/// 电视节目单数据操作类
/// </summary>
public class TVListService
{
/// <summary>
/// 将文件对象封装到List集合中并返回
/// </summary>
/// <param name="path">节目单文件路径</param>
/// <param name="tvDate">节目单日期</param>
/// <returns>返回电视节目单和节目单日期</returns>
public List<TVList> LoadTVList(string path,out string tvDate)
{
//创建文件流和文件读取器
FileStream fs = new FileStream(path, FileMode.Open);
StreamReader sr = new StreamReader(fs,Encoding.Default);
tvDate = sr.ReadLine(); //读取文本第一行的电视节目日期
sr.ReadLine();//读取空行
//循环读取电视节目列表到最后一行终止
string content = string.Empty;
List<TVList> list = new List<TVList>();
string[] array = null; //保存一行分割后的内容
while (true)
{
content = sr.ReadLine();
if (content == null || content.Length == 0)//读取到空的内容处,跳出循环
{
break;
}
else
{
array = content.Split(Convert.ToChar("#"));
list.Add(new TVList()
{
TVTime =array[0],
Channel=array[1],
TVName=array[2]
});
}
}
//关闭文件流,读取器
fs.Close();
sr.Close();
return list;
}
}
}
步骤三:加载按钮编写窗体程序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TVListProgram
{
public partial class FrmTVList : Form
{
public FrmTVList()
{
InitializeComponent();
this.dgvTVList.AutoGenerateColumns = false;
}
TVListService objTVListService = new TVListService();
private void dgvTVList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void btnLoadTVList_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
string tvDate = string.Empty;
List<TVList> list= objTVListService.LoadTVList(ofd.FileName,out tvDate);
this.dgvTVList.DataSource = list;
this.lblTVDate.Text = tvDate;
}
}
}
}