简体   繁体   中英

Parsing CSV into datagrid WinForms

my first question on here. I have gotten myself stuck on something very simple.

I have successfully read a csv and parsed it into a datagrid. My issue is I have a dataset where there is missing data for one of the columns. Editing the dataset is not a possibility.

My code to open and read then parse the csv:

private void ContractsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        DataTable table = new DataTable();
        table.Columns.Add("Vehicle ID", typeof(string));
        table.Columns.Add("Booked_date_year", typeof(string));
        table.Columns.Add("Booked_date_month", typeof(string));
        table.Columns.Add("Booked_date_day", typeof(string));
        table.Columns.Add("Booked_date_week_number", typeof(string));
        table.Columns.Add("Booked_date_day_of_month", typeof(string));
        table.Columns.Add("Number of Days Booked", typeof(string));
        table.Columns.Add("Booking Status", typeof(string));
        table.Columns.Add("Customer Name", typeof(string));
        table.Columns.Add("Customer Email", typeof(string));
        table.Columns.Add("Customer Telephone", typeof(string));

        dataGridView1.DataSource = table;

        string[] lines = File.ReadAllLines("*Hiding this filepath as it included my name*");
        string[] values;


        for (int i = 0; i < lines.Length; i++)
        {
            values = lines[i].ToString().Split(',');
            string[] row = new string[values.Length];

            for (int j = 0; j < values.Length; j++)
            {
                row[j] = values[j].Trim();
            }
            table.Rows.Add(row);
        }
    }

I want to be able to recognise the missing value and therefore miss/ replace with a default value for it as my datagrid is being populated. The current result is that the customer telephone is missing a value where the Booked_date_day should be. My aim is not to recognise just Booked_date_day as missing a value but to actively be able to check if any of the columns should be missing a value.

I have some ideas:

  1. I append every value into an array and check it against some rules for each of the values ie the Booked_date_month should be one of the months Jan, Feb etc.

  2. Not really a second idea (more like a last resort), only recognise Booked_date_day to have an empty value on each row. (this is bad practice hence I want to avoid this)

I would much appreciate any help you can provide. Also let me know if there is anything I can work on when it comes to asking questions: :)

If you ever wondered how to read a CSV file and populate the content of the CSV onto a Datagridview of your Windows Form Application then you are in the right place. Well, there's always a hard way to do stuff and there's an easy way. In this article, we are going to share an effective yet easy way to read CSV and display the content on a Datagridview in the form of rows and columns.

Reading The CSV File

using System.Linq;
using System.Data;
using Microsoft.VisualBasic.FileIO; // This namespace usage is important or else TextFieldParser method will lead to error
using System.IO;
 
namespace CSVApp
{
    public class ReadCSV
    {
        public DataTable readCSV;
 
        public ReadCSV(string fileName, bool firstRowContainsFieldNames = true)
        {
            readCSV = GenerateDataTable(fileName, firstRowContainsFieldNames);
        }
 
        private static DataTable GenerateDataTable(string fileName, bool firstRowContainsFieldNames = true)
        {
            DataTable result = new DataTable();
 
            if (fileName == "")
            {
                return result;
            }
 
            string delimiters = ",";
            string extension = Path.GetExtension(fileName);
 
            if (extension.ToLower() == "txt")
                delimiters = "\t";
            else if (extension.ToLower() == "csv")
                delimiters = ",";
 
            using (TextFieldParser tfp = new TextFieldParser(fileName))
            {
                tfp.SetDelimiters(delimiters);
 
                // Get The Column Names
                if (!tfp.EndOfData)
                {
                    string[] fields = tfp.ReadFields();
 
                    for (int i = 0; i < fields.Count(); i++)
                    {
                        if (firstRowContainsFieldNames)
                            result.Columns.Add(fields[i]);
                        else
                            result.Columns.Add("Col" + i);
                    }
 
                    // If first line is data then add it
                    if (!firstRowContainsFieldNames)
                        result.Rows.Add(fields);
                }
 
                // Get Remaining Rows from the CSV
                while (!tfp.EndOfData)
                    result.Rows.Add(tfp.ReadFields());
            }
 
            return result;
        }
    }
}

Use from here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM