.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> DataGrid >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

DataGrid To CSV in a very Simple Way!

Posted By:Hefin Dsouza       Posted Date: April 29, 2009    Points: 10    Category: DataGrid    URL: http://www.dotnetspark.com  
 

The Following method can be used to save the contents from a DataGrid or DataSet to a CSV format in a very simple way.


private void SaveGridToCSV()

{

StreamWriter strW = new StreamWriter("C:\\Dummy.csv"), false);

DataTable dt = dSet.Tables[0];

     int iColCount = dt.Columns.Count;

     for (int i = 0; i < iColCount; i++)

     {

          strW.Write(dt.Columns[i]); //To Write the Headers

           if (i < iColCount - 1)

           {

                strW.Write(",");

}

}

       strW.Write(strW.NewLine);

     foreach (DataRow dr in dt.Rows)

     {

for (int i = 0; i < iColCount; i++)

           {

                if (dr[i]!=null)

                {

strW.Write(dr[i].ToString()); //Writing the Data

}

                if (i < iColCount - 1)

                {

                     strW.Write(",");

}

           }

            strW.Write(strW.NewLine);

     }

strW.Close();

}


Regards Hefin Dsouza


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend