C#DataGridView定义了从文件

时间:2017-07-28 16:21:18

标签: c# datagridview openfiledialog

我对编码很陌生,所以我很难直接回答我的问题。 我试图在很多方面(YouTube,堆栈溢出,谷歌)找到我的问题的答案,但无法让我的程序正常运行。

我需要我的程序做的是从m3u文件中获取一个值到我数据表中的相应单元格中,而不是读取并添加绝对所有内容。

我在网上找到的主要是如何阅读text / csv / excel并从文件本身导入所有数据,这不是我真正需要的或代码,我不明白如何实现我的使用,如那个问题:Reading from .txt file, then exporting data to DataGridView

我已经定义了应该" suck"来自m3u文件的数据。

文件m3u文件结构是:

  

#EXTINF:-1 tvg-ID ="" tvg-name =" ==== Example1 ====" TVG-标志="" group-title ="",==== Example1 ====
  thestreamingsource1.com
  #EXTINF:-1 tvg-ID ="" tvg-name =" ==== Example2 ====" TVG-标志="" group-title ="",==== Example2 ====
  thestreamingsource2.com
  #EXTINF:-1 tvg-ID ="" tvg-name =" ==== Example3 ====" TVG-标志="" group-title ="",==== Example3 ====
  thestreamingsource3.com
  #EXTINF:-1 tvg-ID ="" tvg-name =" ==== Example4 ====" TVG-标志="" group-title ="",==== Example4 ====
  thestreamingsource4.com

我需要程序只从值结构中获取以下内容: tvg-ID(如果它是空的,那没关系)。 TVG名。 tvg-logo(如果它是空的,那没关系)。 基的标题。

到目前为止,我有一个字符串,它读取文件的所有内容,数据网格已准备好接受数据。

表单背后的代码是:

public class ThisClass
{
    DataGridView my_datagridview = new DataGridView();
    DataTable my_datatable = new DataTable();

    // Constructor and other methods are in this class,
    // but not showed here...

    private void btnRead_Click(object sender, EventArgs e)
    {
        // Some codes are hidden here...

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string sFileName = openFileDialog1.FileName;               
            string[] alltext = File.ReadAllLines(sFileName);
            foreach (string text_line in alltext)
            {
               // MessageBox.Show(text_line);
            }
        }
    }
}

表单看起来像这样: Read M3u UI

对不起如果问题已经回答,但我找不到解决方案。

如果你能提供帮助,我很高兴。

感谢。

1 个答案:

答案 0 :(得分:0)

这应该让你前进:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

using System.Text.RegularExpressions;

namespace DataGridView_45378237
{


    public partial class Form1 : Form
    {

        DataGridView my_datagridview = new DataGridView();//the DataGridView which will be put on the form
        BindingList<MyDatagridviewEntry> myDataGridviewSource = new BindingList<MyDatagridviewEntry>();//the BindingList from which the DataGridView will pull its data


        public Form1()
        {
            InitializeComponent();
            InitializeDataGridView();//set the initial settings of the DataGridView
        }

        private void InitializeDataGridView()
        {
            my_datagridview.Location = new Point(this.Location.X + 15, this.Location.Y + 15);//define where to place it in the form(you could obviously just place one directly where you want using the wysiwyg)
            this.Controls.Add(my_datagridview);

            my_datagridview.AutoSize = true;
            my_datagridview.AutoGenerateColumns = true;
            my_datagridview.DataSource = myDataGridviewSource;//link the DataGridView with the BindingSource

        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = @"C:\";
            openFileDialog1.Title = "Browse Text Files";

            openFileDialog1.CheckFileExists = true;
            openFileDialog1.CheckPathExists = true;

            openFileDialog1.DefaultExt = "m3u";
            openFileDialog1.Filter = "All files (*.*)|*.*|m3u files (*.m3u)|*.m3u";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            openFileDialog1.ReadOnlyChecked = true;
            openFileDialog1.ShowReadOnly = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string sFileName = openFileDialog1.FileName;
                FillDataGridFromFile(sFileName);//send the file to get parsed
            }
        }

        private void FillDataGridFromFile(string incomingFilePath)
        {
            //empty the list
            myDataGridviewSource.Clear();//you may or may not want this... I don't know your full requirements...

            //fill the list
            using (StreamReader sr = new StreamReader(incomingFilePath))
            {
                string currentLine = string.Empty;

                while ((currentLine = sr.ReadLine()) != null)
                {
                    /*This is not how I would write the production code,
                     * but for the sake of this example, this format works well
                     so that you know what is being done and why.*/
                    string[] splittedString = currentLine.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    string f1 = splittedString.Length > 0 ? splittedString[0] : string.Empty;//if splittedString has more than 0 entries, the use entry[0], else use string.empty
                    string f2 = splittedString.Length > 1 ? splittedString[1] : string.Empty;//if splittedString has more than 1 entries, the use entry[1], else use string.empty
                    string f3 = GetTVGNameFromString(splittedString[0]);//Extract the text from within the string
                    string f4 = splittedString.Length > 3 ? splittedString[3] : string.Empty;//if splittedString has more than 3 entries, the use entry[3], else use string.empty
                    /**/

                    //add the entry to the BindingSource
                    myDataGridviewSource.Add(new MyDatagridviewEntry { Col1 = f1, Col2 = f2, Col3 = f3, Col4 = f4 });
                }
            }
        }



        private string GetTVGNameFromString(string incomingString)
        {
            string retval = string.Empty;
            Regex rgx = new Regex("tvg-name=\"([^\"]*)\"");//use a grouping regex to find what you are looking for
            if (rgx.IsMatch(incomingString))
            {
                return rgx.Matches(incomingString)[0].Groups[1].Value;
            }
            return retval;
        }
    }



    public class MyDatagridviewEntry
    {
        public string Col1 { get; set; }
        public string Col2 { get; set; }
        public string Col3 { get; set; }
        public string Col4 { get; set; }
    }
}