我该如何将GridView.DataSource
导出到数据表或数据集中?
假设您的DataSource是DataTable类型,您可以直接这样做:
myGridView.DataSource as DataTable
datagridview.DataSource = dataTable
,但是当我想通过这种方式从 DataSource
中读取时,会抛出无效转换异常,错误信息为:无法将类型为 'System.Windows.Forms.BindingSource' 的对象强制转换为类型 'System.Data.DataTable'。
- Behzad你应该将 DataSource
先转换为 BindingSource
,参考示例
BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource
DataTable tCxC = (DataTable) bs.DataSource;
拥有tCxC
的数据,你可以做任何事情。
个人而言,我会选择:
DataTable tbl = Gridview1.DataSource as DataTable;
支持文档:MSDN“as”的文档
Ambu,
我遇到了和你一样的问题,这是我用来解决它的代码。虽然我不使用页脚行部分来完成我的目的,但我在这段代码中包含了它。
DataTable dt = new DataTable();
// add the columns to the datatable
if (GridView1.HeaderRow != null)
{
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
dt.Columns.Add(GridView1.HeaderRow.Cells[i].Text);
}
}
// add each of the data rows to the table
foreach (GridViewRow row in GridView1.Rows)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dr[i] = row.Cells[i].Text.Replace(" ","");
}
dt.Rows.Add(dr);
}
// add the footer row to the table
if (GridView1.FooterRow != null)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < GridView1.FooterRow.Cells.Count; i++)
{
dr[i] = GridView1.FooterRow.Cells[i].Text.Replace(" ","");
}
dt.Rows.Add(dr);
}
如果您在以下位置执行gridview.bind()
:
if(!IsPostBack)
{
//your gridview bind code here...
}
您可以在函数中使用 DataTable dt = Gridview1.DataSource as DataTable;
来检索数据表。
但是,当我单击按钮时将数据表绑定到网格视图,并记录到微软文档中:
HTTP是一种无状态协议。这意味着Web服务器将每个请求的HTTP页面视为独立的请求。服务器不保留在先前请求中使用的变量值的任何知识。
如果您有相同的条件,那么我建议您使用Session
来保持该值。
Session["oldData"]=Gridview1.DataSource;
在那之后,当页面重新加载时,您可以调用该值。
DataTable dt=(DataTable)Session["oldData"];
References: https://msdn.microsoft.com/en-us/library/ms178581(v=vs.110).aspx#Anchor_0
https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/
我使用了下面这行代码,它有效,请尝试
DataTable dt = dataSource.Tables[0];
虽然有点晚,但这很有帮助。我只是为了以后参考而发布。
DataTable dt = new DataTable();
Data.DataView dv = default(Data.DataView);
dv = (Data.DataView)ds.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();