Home
Manage Your Code
Snippet: Convert DataTable to Separated Values (C#)
Title: Convert DataTable to Separated Values Language: C#
Description: Converts a System.Data.DataTable to a set of values separated the the value of the separator argument. Views: 113
Author: Glenn Bunter Date Added: 10/2/2007
Copy Code  
1/// <summary>
2		/// Converts to separated values.
3		/// </summary>
4		/// <param name="table">The table.</param>
5		/// <param name="firstRowColumnHeader">if set to <c>true</c> the first row will contain the column names.</param>
6		/// <param name="separator">The separator.</param>
7		/// <returns></returns>
8		public static string ConvertToSeparatedValues( DataTable table, bool firstRowColumnHeader, char separator )
9		{
10			StringBuilder sb = new StringBuilder();
11
12			if ( firstRowColumnHeader )
13			{
14				foreach ( DataColumn column in table.Columns )
15				{
16					sb.Append( column.ColumnName );
17					sb.Append( separator );
18				}
19
20				sb.Remove( sb.Length - 1, 1 );
21				sb.Append( "\r\n" );
22			}
23
24			foreach ( DataRow row in table.Rows )
25			{
26				StringBuilder sbInternal = new StringBuilder();
27
28				for ( int i = 0; i < table.Columns.Count; i++ )
29				{
30					string data = row[i].ToString();
31
32					if ( data.Contains( separator.ToString() ) )
33					{
34						throw new FormatException( "Unable to continue because the data contains the separator." );
35					}
36
37					sbInternal.Append( data );
38					sbInternal.Append( separator );
39				}
40
41				sbInternal.Remove( sbInternal.Length - 1, 1 );
42				sbInternal.Append( "\r\n" );
43
44				sb.Append( sbInternal.ToString() );
45			}
46
47			return sb.ToString();
48		}
Notes
If the value contains the separator a FormatException is thrown.