List of Exercises

Parse csv or text Fileto Datatable in C#

	
    private void Select_csv_File_Click(object sender, EventArgs e)
    {
      OpenFileDialog opf = new OpenFileDialog();
      opf.Filter = "csv File|*.csv|Text File|*.txt|All Files|*.*";
      if (opf.ShowDialog() == DialogResult.OK)
      {
        string[] lines = System.IO.File.ReadAllLines(opf.FileName);
        string[][] data = new string[lines.Length][];
        int i = 0;
        foreach (string line in lines)
        {
          data[i] = line.Split(del.Text.ToCharArray());
          i++;
        }
        dataGridView1.DataSource = array2dt<string>(data);
      }
    }
    public static DataTable array2dt<T>(T[][] arr)
    {
      DataTable dt = new DataTable();
      // create columns
      for (int i = 0; i < arr[0].Length; i++)
      {
        dt.Columns.Add();
      }
      for (int j = 0; j < arr.Length; j++)
      {
        // create a DataRow using .NewRow()
        DataRow row = dt.NewRow();
        // iterate over all columns to fill the row
        for (int i = 0; i < arr[j].Length; i++)
        {
          row[i] = arr[j][i];
        }
        // add the current row to the DataTable
        dt.Rows.Add(row);
      }
      return dt;
    }
  }   
	


Download the project of Visual Studio 2013 in DropBox Download


Parse csv File to DataTable in c# .net || Read Text file to DataTable


Video Thumbnail