Hi,
I got the error in my coding.i wrote the code for conversion of gridviewdata to excel.i wrote the code it shows the following error:
Unable to cast object of type 'System.Data.DataTable' to type 'System.Data.DataSet'.
namespace marsweb.imageimpacts
{
public partial class ReportPage : Form
{
public ReportPage()
{
InitializeComponent();
}
public void reportsgridview()
{
SqlConnection con = new SqlConnection("data source=mars-104;initial catalog=marsweb;integrated security=true");
SqlCommand cmd = new SqlCommand("select InvoiceNo,OrderNo, convert(varchar(15),ondate,105) as [OnDate],convert(varchar(15),invoicedate,105) as [InvoiceDate] ,NetAmount,NetVat,TAmount from tbl_report2", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
if (con.State == ConnectionState.Closed)
{
con.Open();
}
da.Fill(dt);
if (con.State == ConnectionState.Open)
{
con.Close();
}
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
}
else
{
}
}
public void getorderno()
{
SqlConnection con = new SqlConnection("data source=mars-104;intial catalog=marsweb;integrated security=true");
SqlCommand cmd = new SqlCommand("select orderno from tbl_report2 where invoiceno=@invoiceno", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
}
private void btn_newinvoice_Click(object sender, EventArgs e)
{
NewInvoice np = new NewInvoice();
np.Show();
this.Hide();
}
private void btn_homepage_Click(object sender, EventArgs e)
{
HomePage hp = new HomePage();
hp.Show();
this.Hide();
}
private void ReportPage_Load(object sender, EventArgs e)
{
reportsgridview();
DataTable dt = (DataTable)GridView1.DataSource;//error shows here only
convertoexcel(dt);
}
public string convertoexcel(DataSet ds)
{
string filename;
Microsoft.Office.Interop.Excel.ApplicationClass excelapp = new Microsoft.Office.Interop.Excel.ApplicationClass();
excelapp.Application.Workbooks.Add(Type.Missing);
excelapp.Columns.ColumnWidth = 30;
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
excelapp.Cells[1, i + 1] = ds.Tables[0].Columns[i].ColumnName;
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
excelapp.Cells[i + 2, j + 1] = ds.Tables[0].Rows[i][j].ToString();
}
}
filename = "f:\\Reports.xls";
if (filename != string.Empty)
{
excelapp.ActiveWorkbook.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel5, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
excelapp.ActiveWorkbook.Saved = true;
excelapp.Quit();
}
return filename;
}
}
}
Best,
Sudheep.
Best,
Sudheep.