提取文本中的数据并显示到DateGridView控件


                                    

创建类 Data_ApartAhow,定义属性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Data_ApartAhow
{
    /// <summary>
    /// 频道类(实体类)
    /// </summary>
    class TVProgram
    {
        public string PlayTime{get; set;}  //属性
        public string Channel { get; set; }
        public string MyProperty { get; set; }
    }
}

主程序

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;

using System.IO;  //添加命名控件

namespace Data_ApartAhow
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
       ///加载节目单
        private void button1_Click(object sender, EventArgs e)
        {
            ///创建文件流与读取器
            FileStream fs = new FileStream("TVPrograms1.txt", FileMode.Open); //当前debug目录下
            StreamReader sr = new StreamReader(fs, Encoding.Default);
            //读取节目时间
            this.label1.Text = sr.ReadLine();
            //读取空行
            sr.ReadLine();
            //创建对象容器
            List<TVProgram> list = new List<TVProgram>();
            string content = string.Empty;  //用于保存一行的内容
            string[] itemArray = null;      //用于保存一行分割后的内容
            while (true)
            {
                content = sr.ReadLine();
                if(content==null || content.Length == 0)
                {
                    break;
                }
                else
                {
                    ///将播放时间、频道、界面分割
                    itemArray = content.Split('t');
                    ///封装节目信息
                    list.Add(new TVProgram()
                    {
                        PlayTime = itemArray[0],
                        Channel = itemArray[1],
                        MyProperty=itemArray[2]                   
                    });
                }
            }
            //显示对象
            this.dataGridView1.DataSource = list;
            //关闭文件流和读取器
            sr.Close();
            fs.Close();
        }
    }
}