broccoli_soup
broccoli_soup

Reputation: 309

Populating part of a DataGridView from CSV

I would like to populate the first several columns with data from a CSV file

The code I am using:

...
   DataTable dataTable = (DataTable)readCsvTable(openFileDialog1.FileName);
   if (dataTable != null) dataGridViewQuestions.DataSource = dataTable; 
...


 private DataTable readCsvTable(string filename) 
    {
        DataTable dtDataSource = new DataTable();

        try
        {
            string[] fileContent = File.ReadAllLines(filename);

            if (fileContent.Count() > 0)
            {
                //Create data table columns
                string[] columns = fileContent[0].Split(',');
                for (int i = 0; i < columns.Count(); i++)
                {
                    dtDataSource.Columns.Add(columns[i]);
                }

                //Add row data
                for (int i = 1; i < fileContent.Count(); i++)
                {
                    string[] rowData = fileContent[i].Split(',');
                    dtDataSource.Rows.Add(rowData);
                }
            }
        }
        catch (Exception ex) {
            ...
            //error msgbox
            ...
            return null;
        }
        return dtDataSource;
    }

The problem:

When AutoGenerateColumns = true - the code results in additional columns (with the same names as the first several columns already in the DataGridView in case of files exported by the same application) being added to the gridView and filled with the appropriate data.

When AutoGenerateColumns = false - the above code adds the right number of rows to the table, and no new columns are added but the rows are empty.

Already tried:

Calling the columns in the CSV file by the column's HeaderText and the column's control name, making a CSV file with the same number of columns as the DataGridView and making files with fewer columns, no difference.

Upvotes: 0

Views: 1433

Answers (2)

Civa
Civa

Reputation: 2176

if the data populating from When "AutoGenerateColumns = true" use it. in that if the previous columns is your problem then you can create new instance to that datagridview;

...
if (dataTable != null)
{
    dataGridViewQuestions = new DataGridView();
    dataGridViewQuestions.DataSource = dataTable;
}
...

Upvotes: 1

Po-ta-toe
Po-ta-toe

Reputation: 732

I've just tried simulating this and it works as expected. Are you getting any exceptions thrown when switching files?

You could try setting the datasource to null before attempting to parse the files so you can see if it gets that far?

dataGridViewQuestions.DataSource = null;
DataTable dataTable = readCsvTable(openFileDialog1.FileName);
if (dataTable != null) 
     dataGridViewQuestions.DataSource = dataTable; 

Upvotes: 1

Related Questions