Ren
Ren

Reputation: 775

Load text to datagridview

I have point files like:
Example point file

I have created code that allows users to select the files from a dialog box and it will populate the data to the gridview.

private void cmdload_Click(object sender, EventArgs e)
{
    DataTable table = new DataTable();
    table.Columns.Add("Point");
    table.Columns.Add("X");
    table.Columns.Add("Y");
    table.Columns.Add("Z");
    table.Columns.Add("R");
    table.Columns.Add("A");
    table.Columns.Add("B");
    table.Columns.Add("C");
    Stream myStream = null;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "C:\\"; 
    openFileDialog1.Filter = "Data Files (*.PNT)|*.PNT";
    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)
                        {
                            string[] parts = line.Split(' ');
                            table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7]);
                        }
                        dataGridView1.DataSource = table;
                    }
                }
            }
        }

        catch (Exception ex) // you need to add the catch block if yo are using try block
        {
            MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
        }

    }
}  

This code works fine, however the datagridview does not display the value.

Example output

Upvotes: 2

Views: 188

Answers (1)

Junaith
Junaith

Reputation: 3388

If you are not creating the DataGridView columns through code then you have to set the DataPropertyName of the DataGridViewColumn to the columns ids in the DataTable.

Sample code:

dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
col1.Name = "Point";
col1.HeaderText = "Point";
col1.DataPropertyName = "Point";
dataGridView1.Columns.Add(col1)

The other way is to set AutoGenerateColumns property to true to create the required columns automatically and bind the data to the DataTable. By this you don't have to create columns through code like in the above sample code.

dataGridView1.AutoGenerateColumns = true;

Upvotes: 1

Related Questions