O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required