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
DataTablecontaining the Orders table from Northwind. TheGetString( )method in this solution is called to convert theDataTableinto a string similar to one that is generated by theGetString( )method of the ADORecordset. The string is displayed in a text box on the form.GetString( )This method mimics the functionality of the
GetString( )method of the ADORecordset. 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 private const String ORDERS_TABLE = "Orders"; // . . . private void goButton_Click(object sender, System.EventArgs e) { // Fill the Order table. SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Orders", ConfigurationSettings.AppSettings["Sql_ConnectString"]); DataTable dt = new DataTable(ORDERS_TABLE); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access