将.txt数据文件加载到DataGridView

时间:2014-03-06 07:17:50

标签: c# gridview

我有一个开放点文件的代码并读取数据文件:

private void cmdload_Click(object sender, EventArgs e)
{
    Stream myStream = null;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "\\Yamaha";
    openFileDialog1.FilterIndex = 2;
    openFileDialog1.RestoreDirectory = true;

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        try
        {
            if ((myStream = openFileDialog1.OpenFile()) != null)
            {
                using (myStream)
                {
                    string filename = openFileDialog1.FileName;
                    using (var reader = File.OpenText(@filename))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            //Do fetch data and paste to gridview operation
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
        }
    }
}

现在我陷入了while循环。我希望循环遍历文件并获取所有数据并将其粘贴到gridview上。

我的网格视图如下:

我的文字文件如下:

1 个答案:

答案 0 :(得分:1)

如果您的文件不是那么大,那么使用linq会非常简单。您只需要读取所有行解析每一行并设置GridView的DataSource。

private void cmdload_Click(object sender, EventArgs e)
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "\\Yamaha";
    openFileDialog1.FilterIndex = 2;
    openFileDialog1.RestoreDirectory = true;

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
       try
       {
           string[] fileLines= System.IO.File.ReadAllLines(openFileDialog1.FileName);
           IEnumerable<string[]> splitedLines = fileLines.Select(c => c.Split(new string[]{" "}, StringSplitOptions.RemoveEmptyEntries));
           var data = splitedLines.Select(c => new
           {
               Point = c[0],
               X = c[2],//c[1] would be "=" sign
               Y = c[3],
               Z = c[4],
               R = c[5],
               A = c[6],
               B = c[7],
               C = c[8]
           });
           dataGridView1.DataSource = data.ToArray();
        }
        catch (Exception ex)
        {
             MessageBox.Show("Error: Something is not right. Original error: " + ex.Message);
        }
    }
}