从CSV文件中读取数据

时间:2022-04-20 03:04:09

I am looking to store values from a CSV file with two Columns, I have the following class ReadFromCSVhandling the reading of the CSV file but I am having difficulty using this list to display the contents once a button is clicked. The code I have to read the CSV file is as follows;

我希望存储具有两个列的CSV文件中的值,我有以下类ReadFromCSV处理CSV文件的读取但是我很难使用此列表在单击按钮后显示内容。我必须阅读CSV文件的代码如下;

namespace ELMFS
{
    public class ReadFromCSV
    {
        static void ReadCSV(string[] args)
        {
            List<TextSpeak> TxtSpk = File.ReadAllLines(@"C:\textwords.csv")
                .Skip(1)
                .Select(t => TextSpeak.FromCsv(t))
                .ToList();
        }
    }
    public class TextSpeak
    {
        string Abreviated;
        string Expanded;


        public static TextSpeak FromCsv(string csvLine)
        {
            string[] TxtSpk = csvLine.Split(',');
            TextSpeak textSpeak = new TextSpeak();
            textSpeak.Abreviated = TxtSpk[0];
            textSpeak.Expanded = TxtSpk[1];
            return textSpeak;
        }
    }
}

I am trying to display the textSpeak.Abreviated in a message box but cannot seem to access it from the WPF window.

我试图在消息框中显示textSpeak.Abreviated但似乎无法从WPF窗口访问它。

How do I use this list in other windows within the application?

如何在应用程序中的其他窗口中使用此列表?

any advice would be appreciated!

任何意见,将不胜感激!

Thanks in advance!

提前致谢!

3 个解决方案

#1


1  

First, ReadCSV method should return the generated List object (or you cannot use the list anywhere else).

首先,ReadCSV方法应返回生成的List对象(或者您不能在其他任何地方使用该列表)。

Second, TextSpeak class should have properties so that you can access its member variables outside the class.

其次,TextSpeak类应该具有属性,以便您可以在类外部访问其成员变量。

I.e. something like this should work:

即像这样的东西应该工作:

namespace ELMFS
{
    public class ReadFromCSV
    {
        public static List<TextSpeak> ReadCSV(string[] args)
        {
            List<TextSpeak> TxtSpk = File.ReadAllLines(@"C:\textwords.csv")
                .Skip(1)
                .Select(t => TextSpeak.FromCsv(t))
                .ToList();
            return TxtSpk;
        }
    }
    public class TextSpeak
    {
        public string Abreviated { get; private set; }
        public string Expanded { get; private set; }


        public static TextSpeak FromCsv(string csvLine)
        {
            string[] TxtSpk = csvLine.Split(',');
            TextSpeak textSpeak = new TextSpeak();
            textSpeak.Abreviated = TxtSpk[0];
            textSpeak.Expanded = TxtSpk[1];
            return textSpeak;
        }
    }
}

#2


0  

private void Display(int count)
        {

            textBox1.Text = "";
            for (int i = 0; i <= count ; i++)
            {
                textBox1.Text += ((dataGridView1.Rows[i].Cells[1].Value).ToString()) +  (dataGridView1.Rows[i].Cells[2].Value.ToString()) + Environment.NewLine;

            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {

                // your code here 

                string CSVFilePathName =Path.GetDirectoryName(Application.ExecutablePath).Replace(@"\bin\Debug", @"\NewFolder1\TEST.csv");
                string[] Lines = File.ReadAllLines(CSVFilePathName);
                string[] Fields;
                Fields = Lines[0].Split(new char[] { ',' });
                int Cols = Fields.GetLength(0);
                DataTable dt = new DataTable();
                //1st row must be column names; force lower case to ensure matching later on.
                for (int i = 0; i < Cols; i++)
                    dt.Columns.Add(Fields[i].ToLower(), typeof(string));
                DataRow Row;
                for (int i = 1; i < Lines.GetLength(0); i++)
                {
                    Fields = Lines[i].Split(new char[] { ',' });
                    Row = dt.NewRow();
                    for (int f = 0; f < Cols; f++)
                        Row[f] = Fields[f];
                    dt.Rows.Add(Row);
                }
                dataGridView1.DataSource = dt;

                int count = 0;

                if (dataGridView1.RowCount > 0)
                {

                    count = dataGridView1.Rows.Count;
                }


                buttons  = new Button[count];
                for (int i = 0; i <count; i++)
                {
                    buttons[i] = new Button();
                    buttons[i].Name = "buttons_Click" + i.ToString();
                    buttons[i].Text = "Click";
                    buttons[i].Click += new EventHandler(buttons_Click);
                    this.Controls.Add(buttons[i]);
                    buttons[i].Visible = false;
                }

                buttons[0].Visible = true;
               // buttons[1].Visible = true;

            }


            catch (Exception ex)
            {
                MessageBox.Show("Error is " + ex.ToString());
                throw;
            }
        }
        private void buttons_Click(object sender, EventArgs e)
        {
            int count = dataGridView1.Rows.Count-1;
            if(c <= count)
            {

                if (buttons[c].Name == "buttons_Click" + c.ToString())
                {
                    buttons[c].Visible = false;
                    int j = c;
                    Display(j);
                    if (c != count)
                    {

                        c = c + 1;
                        buttons[c].Visible = true;
                    }

                }

            }
            if (c == count)
            {
                buttons[0].Visible = true;
            }
        }
    }
}

#3


-1  

you just need to import the namespace of the class ReadFromCS, which is in your case ELMFS in the class of the WPF window like this:

你只需要导入类ReadFromCS的命名空间,在你的情况下,在WPF窗口的类中是ELMFS,如下所示:

using ELMFS;

Next, the function ReadCSV need the attribute internal and should return a list, like this (and remove the unused argument):

接下来,函数ReadCSV需要内部属性并且应该返回一个列表,如下所示(并删除未使用的参数):

internal static List<TextSpeak> ReadCSV() {
                 return File.ReadAllLines(@"C:\textwords.csv")
            .Skip(1)
            .Select(t => TextSpeak.FromCsv(t))
            .ToList();

Also make the variables of the class TextSpeak public like this:

还要将TextSpeak类的变量设为公共,如下所示:

public string Abreviated;
public string Expanded;

#1


1  

First, ReadCSV method should return the generated List object (or you cannot use the list anywhere else).

首先,ReadCSV方法应返回生成的List对象(或者您不能在其他任何地方使用该列表)。

Second, TextSpeak class should have properties so that you can access its member variables outside the class.

其次,TextSpeak类应该具有属性,以便您可以在类外部访问其成员变量。

I.e. something like this should work:

即像这样的东西应该工作:

namespace ELMFS
{
    public class ReadFromCSV
    {
        public static List<TextSpeak> ReadCSV(string[] args)
        {
            List<TextSpeak> TxtSpk = File.ReadAllLines(@"C:\textwords.csv")
                .Skip(1)
                .Select(t => TextSpeak.FromCsv(t))
                .ToList();
            return TxtSpk;
        }
    }
    public class TextSpeak
    {
        public string Abreviated { get; private set; }
        public string Expanded { get; private set; }


        public static TextSpeak FromCsv(string csvLine)
        {
            string[] TxtSpk = csvLine.Split(',');
            TextSpeak textSpeak = new TextSpeak();
            textSpeak.Abreviated = TxtSpk[0];
            textSpeak.Expanded = TxtSpk[1];
            return textSpeak;
        }
    }
}

#2


0  

private void Display(int count)
        {

            textBox1.Text = "";
            for (int i = 0; i <= count ; i++)
            {
                textBox1.Text += ((dataGridView1.Rows[i].Cells[1].Value).ToString()) +  (dataGridView1.Rows[i].Cells[2].Value.ToString()) + Environment.NewLine;

            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {

                // your code here 

                string CSVFilePathName =Path.GetDirectoryName(Application.ExecutablePath).Replace(@"\bin\Debug", @"\NewFolder1\TEST.csv");
                string[] Lines = File.ReadAllLines(CSVFilePathName);
                string[] Fields;
                Fields = Lines[0].Split(new char[] { ',' });
                int Cols = Fields.GetLength(0);
                DataTable dt = new DataTable();
                //1st row must be column names; force lower case to ensure matching later on.
                for (int i = 0; i < Cols; i++)
                    dt.Columns.Add(Fields[i].ToLower(), typeof(string));
                DataRow Row;
                for (int i = 1; i < Lines.GetLength(0); i++)
                {
                    Fields = Lines[i].Split(new char[] { ',' });
                    Row = dt.NewRow();
                    for (int f = 0; f < Cols; f++)
                        Row[f] = Fields[f];
                    dt.Rows.Add(Row);
                }
                dataGridView1.DataSource = dt;

                int count = 0;

                if (dataGridView1.RowCount > 0)
                {

                    count = dataGridView1.Rows.Count;
                }


                buttons  = new Button[count];
                for (int i = 0; i <count; i++)
                {
                    buttons[i] = new Button();
                    buttons[i].Name = "buttons_Click" + i.ToString();
                    buttons[i].Text = "Click";
                    buttons[i].Click += new EventHandler(buttons_Click);
                    this.Controls.Add(buttons[i]);
                    buttons[i].Visible = false;
                }

                buttons[0].Visible = true;
               // buttons[1].Visible = true;

            }


            catch (Exception ex)
            {
                MessageBox.Show("Error is " + ex.ToString());
                throw;
            }
        }
        private void buttons_Click(object sender, EventArgs e)
        {
            int count = dataGridView1.Rows.Count-1;
            if(c <= count)
            {

                if (buttons[c].Name == "buttons_Click" + c.ToString())
                {
                    buttons[c].Visible = false;
                    int j = c;
                    Display(j);
                    if (c != count)
                    {

                        c = c + 1;
                        buttons[c].Visible = true;
                    }

                }

            }
            if (c == count)
            {
                buttons[0].Visible = true;
            }
        }
    }
}

#3


-1  

you just need to import the namespace of the class ReadFromCS, which is in your case ELMFS in the class of the WPF window like this:

你只需要导入类ReadFromCS的命名空间,在你的情况下,在WPF窗口的类中是ELMFS,如下所示:

using ELMFS;

Next, the function ReadCSV need the attribute internal and should return a list, like this (and remove the unused argument):

接下来,函数ReadCSV需要内部属性并且应该返回一个列表,如下所示(并删除未使用的参数):

internal static List<TextSpeak> ReadCSV() {
                 return File.ReadAllLines(@"C:\textwords.csv")
            .Skip(1)
            .Select(t => TextSpeak.FromCsv(t))
            .ToList();

Also make the variables of the class TextSpeak public like this:

还要将TextSpeak类的变量设为公共,如下所示:

public string Abreviated;
public string Expanded;