This snippet shows you how to create a simple CSV class which can be used to populate a DataGridView control.
CSV.cs
public class CSV
{
private StreamReader _reader;
private ArrayList _contactCollection;
private ArrayList _record;
public CSV(string filename)
{
_reader = new StreamReader(filename);
}
public ArrayList GetContacts()
{
_contactCollection = new ArrayList();
_record = new ArrayList();
string line = "";
while ((line = _reader.ReadLine()) !=null)
{
object[] record = line.Split(',');
_contactCollection.Add(record);
}
return _contactCollection;
}
}
Usage
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("Name", "Name");
dataGridView1.Columns.Add("Surname", "Surname");
dataGridView1.Columns.Add("Email", "Email");
CSV csvFile = new CSV("contacts.csv");
ArrayList contacts = csvFile.GetContacts();
for (int i = 0; i < contacts.Count; i++ )
{
object[] record = (object[])contacts[i];
dataGridView1.Rows.Add(record);
}
}
2 comments:
instead of dataGridView1 how to read record in dataset?
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