Try it this way:
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataAdapter adapter = null;
DataSet dataset = null;
DataTable dataTable = null;
try
{
using (conn = new SqlConnection("connection string"))
{
conn.Open();
using (cmd = new SqlCommand("sp_web_reports", conn) { CommandType = CommandType.StoredProcedure })
{
cmd.Parameters.AddWithValue("@mode", 50);
cmd.Parameters.AddWithValue("@From_Date", Convert.ToDateTime(txt_from_date.Text));
cmd.Parameters.AddWithValue("@TO_Date", Convert.ToDateTime(txt_to_date.Text));
cmd.Parameters.AddWithValue("@GroupCode", drp_vehicle_group.SelectedValue);
using (adapter = new SqlDataAdapter(cmd))
{
dataset = new DataSet();
adapter.Fill(dataset);
dataTable = dataset.Tables[0];
}
}
}
}
catch (Exception ex)
{
}
The
using
statement has the benefit of cleaning up the adapter, command, and connection objects without writing code to specifically handle that. Furthermore, you should wrap
ALL ADO code with
try/catch
blocks and handle the exceptions appropriately. Defining the various objects before the first
using
statement allows you to examine them in the debugger in the event an exception is raised.
If you want to export to Excel, all you have to do is call
dataTable.WriteXML("filename")
, and Excel 2007+ can read it.