Hendrik Sidaway
Hendrik Sidaway

Reputation: 21

Import Part of CSV to datagridview

What I have is a CSV that I have imported into a Datagridview.

I am now looking for a way to only import the column with the header # and Delay and not all info in the CSV, so any help on this would be appreciated.

Here is the Code I have thus far:

private void button1_Click(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    DialogResult result = openFileDialog1.ShowDialog();

    if (result == DialogResult.OK) // Test result.
    {
        String Fname = openFileDialog1.FileName;
        //String Sname = "export";
        string[] raw_text = System.IO.File.ReadAllLines(Fname);
        string[] data_col = null;
        int x = 0;

        foreach (string text_line in raw_text)
        {
            data_col = text_line.Split(';');
            if (x == 0)
            {
                for (int i = 0; i < data_col.Count(); i++)
                {
                    dt.Columns.Add(data_col[i]);
                }
                x++;
            }
            else
            {
                dt.Rows.Add(data_col);
            }
        }

        dataGridView1.DataSource = dt;
    }
}

Upvotes: 0

Views: 1065

Answers (2)

Filburt
Filburt

Reputation: 18061

Using TextFieldParser can make handling CVS input less brittle:

// add this using statement for TextFieldParser - needs reference to Microsoft.VisualBasic assembly
using Microsoft.VisualBasic.FileIO;
...

// TextFieldParser implements IDisposable so you can let a using block take care of opening and closing
using (TextFieldParser parser = new TextFieldParser(Fname))
{
    // configure your parser to your needs
    parser.TextFieldType = FieldType.Delimited;
    parser.Delimiters = new string[] { ";" };
    parser.HasFieldsEnclosedInQuotes = false; // no messy code if your data comes with quotes: ...;"text value";"another";...

    // read the first line with your headers
    string[] fields = parser.ReadFields();

    // add the desired headers with the desired data type
    dt.Columns.Add(fields[2], typeof(string));
    dt.Columns.Add(fields[4], typeof(string));

    // read the rest of the lines from your file
    while (!parser.EndOfData)
    {
        // all fields from one line
        string[] line = parser.ReadFields();

        // create a new row <-- this is missing in your code
        DataRow row = dt.NewRow();

        // put data values; cast if needed - this example uses string type columns
        row[0] = line[2];
        row[1] = line[4];

        // add the newly created and filled row
        dt.Rows.Add(row);
    }
}

// asign to DGV
this.dataGridView1.DataSource = dt;

Upvotes: 0

Ortund
Ortund

Reputation: 8245

When I read from CSV files, I create a list of values that I want for each row and use that list as the basis for my INSERT statement to the database.

I know where to find the data I want in the CSV file so I specifically target those items while I'm building my list of parameters for the query.

See the code below:

// Read the file content from the function parameter.
string content = System.Text.Encoding.ASCII.GetString(bytes);

// Split the content into an array where each array item is a line for
// each row of data.
// The Replace simply removes the CarriageReturn LineFeed characters from
// the source text and replaces them with a Pipe character (`|`)
// and then does the split from that character.
// This is just personal preference to do it this way
string[] data = content.Replace("\r\n", "|").Split('|');

// Loop through each row and extract the data you want.
// Note that each value is in a fixed position in the row.
foreach (string row in data)
{
    if (!String.IsNullOrEmpty(row))
    {
        string[] cols = row.Split(';');

        List<MySqlParameter> args = new List<MySqlParameter>();
        args.Add(new MySqlParameter("@sid", Session["storeid"]));
        args.Add(new MySqlParameter("@name", cols[0]));
        args.Add(new MySqlParameter("@con", cols[3]));

        try
        {
            // Insert the data to the database.
        }
        catch (Exception ex)
        {
            // Report an error.
        }
    }
}

In the same way, you could build your list/dataset/whatever as a data source for your datagridview. I would build a table.

Here's a mockup (I haven't got time to test it right now but it should get you on the right track).

DataTable table = new DataTable();
table.Columns.Add("#");
table.Columns.Add("Delay");

foreach (var line in raw_text)
{
    DataRow row = table.NewRow();
    row[0] = line[0]; // The # value you want.
    row[1] = line[1]; // The Delay value you want.

    table.Rows.Add(row);
}

DataGridView1.DataSource = table;
DataGridView1.DataBind();

Upvotes: 1

Related Questions