[ Team LiB ]Recipe 5.11 Exporting the Results of a Query as a String
Problem
You need to export the results of a query to a string in a manner similar to the GetString(
) method of the ADO Recordset.
Solution
Write a routine to mimic the functionality of the ADO Recordset's GetString( ) method.
The sample code contains an event handler and a method:
Go Button.Click
Sets up the sample by creating a DataTable containing the Orders table from
Northwind. The GetString( ) method in this solution is called to convert the
DataTable into a string similar to one that is generated by the GetString( ) method
of the ADO Recordset. The string is displayed in a text box on the form.
GetString( )
This method mimics the functionality of the GetString( ) method of the ADO
Recordset. The method iterates over the collection of rows and columns in the
table appending the field values to a string. Null values are replaced as specified
and column and row delimiters are applied.
The C# code is shown in Example 5-13
.
Example 5-13. File: AdoGetStringForm.cs
// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Text;
using System.Data;
using System.Data.SqlClient;
// Table name constants
// Row delimiter defaults to CARRIAGE RETURN
if(rowDelimiter == null)
rowDelimiter = "\r";
// Null expression defaults to empty string
if(nullExpr == null)
nullExpr = "";
StringBuilder sb = new StringBuilder( );
// Iterate over the collection of rows.
for(int i = 0; i < numRows; i++)
{
// Iterate over the collection of columns.
foreach (object col in dt.Rows[i].ItemArray)
{
// Replace null values as they occur.
String colString = (col == System.DBNull.Value) ?
nullExpr : col.ToString( );
// Add the column value to the string.
sb.Append(colString + columnDelimiter);
}
// Remove the column delimiter on last field.
sb.Remove(sb.Length - columnDelimiter.Length,
columnDelimiter.Length);
// Append row delimiter.
sb.Append(rowDelimiter);
}
[ Team LiB ]