CSV File To DataGridView Control In C#

This snippet shows you how to create a simple CSV class which can be used to populate a DataGridView control.



CSV.cs

  1. public class CSV
  2. {
  3.     private StreamReader _reader;
  4.     private ArrayList _contactCollection;
  5.     private ArrayList _record;
  6.     public CSV(string filename)
  7.     {
  8.         _reader = new StreamReader(filename);
  9.     }
  10.     public ArrayList GetContacts()
  11.     {
  12.         _contactCollection = new ArrayList();
  13.         _record = new ArrayList();
  14.         string line = "";
  15.         while ((line = _reader.ReadLine()) !=null)
  16.         {
  17.             object[] record = line.Split(',');
  18.             _contactCollection.Add(record);
  19.         }
  20.         return _contactCollection;
  21.     }
  22. }

Usage

  1. private void Form1_Load(object sender, EventArgs e)
  2. {
  3.     dataGridView1.Columns.Add("Name", "Name");
  4.     dataGridView1.Columns.Add("Surname", "Surname");
  5.     dataGridView1.Columns.Add("Email", "Email");
  6.     CSV csvFile = new CSV("contacts.csv");
  7.     ArrayList contacts = csvFile.GetContacts();
  8.     for (int i = 0; i < contacts.Count; i++ )
  9.     {
  10.         object[] record = (object[])contacts[i];
  11.         dataGridView1.Rows.Add(record);
  12.     }
  13. }

2 comments:

Unknown said...

instead of dataGridView1 how to read record in dataset?

Unknown said...

Hi Cris, you can set the DataSource property of the DataGridView control with data from a database. For example you can use a DataTable or DataSet class.

Post a Comment