我正试图将a保存GridView
到DataTable
.
我有代码,理论上应该这样做但我不断收到此错误:
第0列不存在
这是我的代码:
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); } }
有关如何解决此问题的任何帮助?
你可以这样做:
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这将表明它有效.
GridView6.DataSource = dt; GridView6.DataBind();
2> 小智..: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); }