Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here i create a function to save data from datagridview to csv file

but i dont know how to add header field

C#
private void button1_Click(object sender, EventArgs e)
{
    string strValue = string.Empty;

    for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
    {
        for (int j = 0; j < dataGridView1.Rows[i].Cells.Count; j++)
        {
            if (!string.IsNullOrEmpty(dataGridView1[j, i].Value.ToString()))
            {
                if (j > 0)
                    strValue = strValue + "," + dataGridView1[j, i].Value.ToString();
                else
                {
                    if (string.IsNullOrEmpty(strValue))
                        strValue = dataGridView1[j, i].Value.ToString();
                    else
                        strValue = strValue + Environment.NewLine + dataGridView1[j, i].Value.ToString();
                }
            }
        }
                
    }
           
            
    string strFile = "c:\\Active Dir File.csv";
    File.WriteAllText(strFile, strValue);
    MessageBox.Show("File Saved in C:");
}
Posted
Updated 13-Sep-11 3:53am
v3

In this case you could start strValue with a literal string which is equal to your header row before you go into your loop.
Alternatively if you have populated the header cells then you can loop through these to build your header row.

If this is your actual code then I would advise you to look at the stringbuilder class as well.
 
Share this answer
 
v2
Comments
Pravin Patil, Mumbai 13-Sep-11 10:12am    
Good solution..
My 5
kami124 13-Sep-11 10:13am    
can u please write the string where exactly i have to write
strValue={"AAA", "BBB", "CCC", "DDD", "EEE", "FFF"}
Paul E Davies 14-Sep-11 4:18am    
Where you set strValue = string.empty would do, you just need to do it before you enter your loops
Do they all use the same layout?

If yes, create a file with that single header line.

Then shell to DOS and merge the files using an old DOS command.

Go to the folder that contains the .CSV files and header file and issue this
command:

copy Header.txt + somefile.csv somefileNEW.csv
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900