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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…