I'm trying to save a GridView
to a DataTable
.
I have code which should in theory do it but I keep getting this error:
Column 0 doesn't exist
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int j = 0; j < GridView1.Rows.Count; j++)
{
DataRow dr;
GridViewRow row = GridView1.Rows[j];
dr = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dr[i] = row.Cells[i].Text;
}
dt.Rows.Add(dr);
}
}
Any help on how to fix this?
you can do something like this:
DataTable dt = new DataTable();
for (int i = 0; i < GridView1.Columns.Count; i++)
{
dt.Columns.Add("column"+i.ToString());
}
foreach (GridViewRow row in GridView1.Rows)
{
DataRow dr = dt.NewRow();
for(int j = 0;j<GridView1.Columns.Count;j++)
{
dr["column" + j.ToString()] = row.Cells[j].Text;
}
dt.Rows.Add(dr);
}
And that will show that it works.
GridView6.DataSource = dt;
GridView6.DataBind();
protected void btnExportExcel_Click(object sender, EventArgs e)
{
DataTable _datatable = new DataTable();
for (int i = 0; i < grdReport.Columns.Count; i++)
{
_datatable.Columns.Add(grdReport.Columns[i].ToString());
}
foreach (GridViewRow row in grdReport.Rows)
{
DataRow dr = _datatable.NewRow();
for (int j = 0; j < grdReport.Columns.Count; j++)
{
if (!row.Cells[j].Text.Equals(" "))
dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
}
_datatable.Rows.Add(dr);
}
ExportDataTableToExcel(_datatable);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With