Ren
Ren

Reputation: 775

Load .txt data files to DataGridView

I have a code to open point file and read the data files:

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);
        }
    }
}

Now I stuck in the while loop. I want the loop to go through the file and fetch all the data and paste it on the gridview.

My gridview is like:

My text file is like:

Upvotes: 0

Views: 1371

Answers (1)

VahidNaderi
VahidNaderi

Reputation: 2488

If your file is not so big, it would be very simple using linq. You just need to read all lines parse each line and set the GridView's 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);
        }
    }
}

Upvotes: 1

Related Questions