Create a data table from a CSV file.

private void Form1_Load(object sender, System.EventArgs e)
{
 this.Size = new System.Drawing.Size(640, 480);
 DataGridView DataGridView1 = new DataGridView();
 DataGridView1.Location = new System.Drawing.Point(0, 0);
 DataGridView1.Size = new System.Drawing.Size(635, 445);
 DataGridView1.Anchor = 15;
 this.Controls.Add(DataGridView1);
 Data.DataTable CsvTable = new Data.DataTable();
 string Filename = "C:\\Temp\\Temp1.csv";
 string[] Fields = null;
 string Delimiter = ",";
 using (Microsoft.VisualBasic.FileIO.TextFieldParser Parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(Filename)) {
  Parser.SetDelimiters(Delimiter);
  while (!Parser.EndOfData) {
   Fields = Parser.ReadFields();
   if (CsvTable.Columns.Count == 0) {
    //This code presumes the first line of data contains the column names.
    foreach (string Field in Fields) {
     string ColumnName = Field;
     while (CsvTable.Columns.Contains(ColumnName)) {
      ColumnName = Conversion.Val(ColumnName) + 1 + "-" + Field;
     }
     CsvTable.Columns.Add(ColumnName, System.Type.GetType("System.String"));
    }
   } else {
    Data.DataRow NewDataRow = CsvTable.NewRow;
    for (int i = 0; i <= Math.Min(CsvTable.Columns.Count - 1, Fields.Length - 1); i++) {
     NewDataRow.Item(i) = Fields(i);
    }
    CsvTable.Rows.Add(NewDataRow);
   }
  }
 }
 DataGridView1.DataSource = CsvTable;
 DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
 DataGridView1.AutoResizeColumns();
}

No comments:

Post a Comment