How to Import Data from or Export Data to CSV or Text File in DataGridView using C#

Let’s start with how to import data from CSV or Text File in DataGridView. So, first of all, you need to read the targeted File to import its content. Here, I used StreamReader to read file. It’s quite simple to read file using StreamReader.


if (System.IO.File.Exists(textBox1.Text))
{
  System.IO.StreamReader fileReader = new StreamReader(textBox1.Text);
                        
   //Checking the end of file's content
   if (fileReader.Peek() != -1)
   {
     string fileRow = fileReader.ReadLine();
     string[] fileDataField = fileRow.Split(',');
   }

 //Close the StreamReader
 fileReader.Close();
}

Have a look at TrialData.csv File’s content.


Name,City,Country,Email,Blog,Cell
A Rahim Khan,kurigram,Bangladesh,khan.rahim@gmail.com,khanrahim.wordpress.com,88-01712876460
A Rahim Khan,Rangpur,Bangladesh,khan.rahim@gmail.com,khanrahim.wordpress.com,88-01712876460
A Rahim Khan,Sylhet,Bangladesh,khan.rahim@gmail.com,khanrahim.wordpress.com,88-01712876460
A Rahim Khan,Naogaon,Bangladesh,khan.rahim@gmail.com,khanrahim.wordpress.com,88-01712876460
A Rahim Khan,Brahman Baria,Bangladesh,khan.rahim@gmail.com,khanrahim.wordpress.com,88-01712876460
A Rahim Khan,Dhaka,Bangladesh,khan.rahim@gmail.com,khanrahim.wordpress.com,88-01712876460
A Rahim Khan,Dhaka,Bangladesh,khan.rahim@gmail.com,khanrahim.wordpress.com,88-01712876460
A Rahim Khan,Dinajpur,Bangladesh,khan.rahim@gmail.com,khanrahim.wordpress.com,88-058161832

First line represents Column Header here. I have to import this set of Data in DataGridView.

Following self-explanatory code snippet shows how to add Columns and insert new Rows programmatically in DataGridView.


fileRow = fileReader.ReadLine();
fileDataField = fileRow.Split(',');
int count = fileDataField.Count();

//Adding Column Header to DataGridView
for (int i = 0; i < count; i++)
{
  DataGridViewTextBoxColumn columnDataGridTextBox = new DataGridViewTextBoxColumn();
  columnDataGridTextBox.Name = fileDataField[i];
  columnDataGridTextBox.HeaderText = fileDataField[i];
  columnDataGridTextBox.Width = 120;
  dataGridView1.Columns.Add(columnDataGridTextBox);
} 

//Adding Data to DataGridView
while (fileReader.Peek() != -1)
{
 fileRow = fileReader.ReadLine();
 fileDataField = fileRow.Split(',');
 dataGridView1.Rows.Add(fileDataField);
}

To export data from a DataGridView to CSV File, I used StreamWriter. StreamWriter Constructor accepts two Parameters; one is file path and the other one is Boolean. For “true” StreamWriter will append the new content at the end of existing content. On the other hand it will erase existing content and write new content for “false” Value.


System.IO.StreamWriter fileWriter = new StreamWriter(textBox1.Text, false);

fileWriter.WriteLine("ABC");

fileWriter.Flush();
fileWriter.Close();

Now, we know how to write in CSV or Text File. Next code snippet shows how to retrieve data from DataGridView.


string columnHeaderText = "";
                
//Collecting DataGridView Column Header Text
int countColumn = dataGridView1.ColumnCount -1;
                
if(countColumn >= 0)
{
  columnHeaderText = dataGridView1.Columns[0].HeaderText;
}

for (int i = 1; i <=countColumn; i++)
{
  columnHeaderText = columnHeaderText + ',' + dataGridView1.Columns[i].HeaderText;
}

//Writing Column Header Text in File
fileWriter.WriteLine(columnHeaderText);

//Collecting Data Rows
foreach (DataGridViewRow dataRowObject in dataGridView1.Rows)
{
 //Checking for New Row in DataGridView 
 if (!dataRowObject.IsNewRow)
 {
   string dataFromGrid = "";

   dataFromGrid = dataRowObject.Cells[0].Value.ToString();

   for (int i = 1; i <= countColumn; i++)
   {
     dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
   }           
   
   //Writing Data Rows in File         
   fileWriter.WriteLine(dataFromGrid);
 }

You can collect the source code here of this example.

Thanks
A Rahim Khan

Advertisements
    • Nazima
    • July 19th, 2011

    Hi Raheem..i am using ur code for importing data from csv file to datagridview.but at place i am getting an exception i.e.System.FormatException String must be one character long.What i have done is i have created a text file and then i saved it as Test.csv.

    if (dataloaded == false)
    {
    try
    {
    delimiter = Convert.ToChar(txtdelimiter.Text);—>Showing System.FormatException String must be one character long.
    }
    catch (Exception exObject)
    {
    MessageBox.Show(exObject.ToString());
    this.Close();
    }
    Can you say me why is it showing like that.

  1. txtdelimiter.Text has no value to convert. That is why it’s throwing this Exception message.

    • urmila
    • September 10th, 2011

    thank you for help

  2. thanks brother,,it’s very helpfull,,
    and what about to convert the csv file to 2 dimensional array? can you help me?
    may the force be with you!!

  3. Thanks for sharing this, it’s the clearest example of the technique I’ve found when googling it. Good logic, clean code.

    • murugan
    • February 24th, 2012

    hai i want insert data wia datagrid ,

    • anto
    • May 23rd, 2012

    i want to calculate 2 cells in my grid view for eg: quantity 1 cell and rate another cell (quantity * rate = amount) how can i multiply and get the answer in run time in cell amount can u help me out

    • mohammed
    • October 29th, 2012

    very nice post , i need your help , i need to import from excel file , then i need to post the added data to the database , actually , i tried and i successfuly import the data but when i use the tableadapter.update , the new added row dosn’t added to the database , i am confused , i need it very much , your help appricated .

  4. Hi there, simply become aware of your blog thru Google, and found
    that it is really informative. I’m going to

    be careful for brussels. I will be grateful in

    case you continue this in future. Lots of other people will likely be
    benefited from your writing. Cheers!

    • kikurt
    • July 9th, 2013

    how to put header in my datagridview? because my csv file has no header. thanks in advance.

    • Muhammad sufiyan
    • August 1st, 2013

    thank you sir..it helps me lot..

    • Musti
    • April 10th, 2014

    Thankuuuuu dude!!! you just saved my ass here big time!!!!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: