Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

c# - How to convert DataSet to DataTable

I am retrieving data from a SQL table so I can display the result on the page as a HTML table. Later I need to be able to save that table as a CSV file.

So far I have figured out how to retrieve the data and fill them in a dataset for display purpose (which is working perfectly)...

        string selectQuery = "SELECT Name, ProductNumber, ListPrice FROM Poduction.Product";

        // Establish the connection to the SQL database 
        SqlConnection conn = ConnectionManager.GetConnection();
        conn.Open();

        // Connect to the SQL database using the above query to get all the data from table.
        SqlDataAdapter myCommand = new SqlDataAdapter(selectQuery, conn);

        // Create and fill a DataSet.
        DataSet ds = new DataSet();
        myCommand.Fill(ds);

and how to save them in a CSV file with the help of following code from: http://www.evontech.com/login/topic/1983.html

    private void exportDataTableToCsv(DataTable formattedDataTable, string filename)
    {
       DataTable toExcel = formattedDataTable.Copy();
       HttpContext context = HttpContext.Current;
       context.Response.Clear();

       foreach (DataColumn column in toExcel.Columns)
       {
          context.Response.Write(column.ColumnName + ",");
       }

       context.Response.Write(Environment.NewLine);
       foreach (DataRow row in toExcel.Rows)
       {
          for (int i = 0; i < toExcel.Columns.Count; i++)
          {
             context.Response.Write(row.ToString().Replace(",", string.Empty) + ",");
          }

          context.Response.Write(Environment.NewLine);
       }

       context.Response.ContentType = "text/csv";
       context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");
       context.Response.End();
    }

Now my problem is how do I convert this DataSet to DataTable? I have tried the way described here with NO luck: http://www.ezineasp.net/post/ASP-Net-C-sharp-Convert-DataSet-to-DataTable.aspx

Can anyone help me?

question from:https://stackoverflow.com/questions/8983277/how-to-convert-dataset-to-datatable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A DataSet already contains DataTables. You can just use:

DataTable firstTable = dataSet.Tables[0];

or by name:

DataTable customerTable = dataSet.Tables["Customer"];

Note that you should have using statements for your SQL code, to ensure the connection is disposed properly:

using (SqlConnection conn = ...)
{
    // Code here...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...