【发布时间】:2010-10-21 14:39:43
【问题描述】:
如何将GridView.DataSource 导出到数据表或数据集?
【问题讨论】:
-
GridView.DataSource指向的对象的类型是什么?
如何将GridView.DataSource 导出到数据表或数据集?
【问题讨论】:
假设您的 DataSource 是 DataTable 类型,您可以这样做:
myGridView.DataSource as DataTable
【讨论】:
datagridview.DataSource = dataTable,但是当我想通过这种方式从DataSource 读取它时,通过消息抛出无效的强制转换异常:Unable to cast object of type 'System.Windows.Forms.BindingSource' to type 'System.Data.DataTable'.
你应该先将DataSource转换成BindingSource,看例子
BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource
DataTable tCxC = (DataTable) bs.DataSource;
有了tCxC的数据,你可以做任何事。
【讨论】:
我个人会选择:
DataTable tbl = Gridview1.DataSource as DataTable;
这将允许您测试 null,因为这会导致 DataTable 对象或 null。使用 (DataTable)Gridview1.DataSource 将其转换为 DataTable 会导致崩溃错误,以防 DataSource 实际上是 DataSet 甚至是某种集合。
【讨论】:
安布,
我遇到了和你一样的问题,这是我用来解决问题的代码。虽然,我没有出于我的目的使用页脚行部分,但我确实将它包含在此代码中。
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;来检索数据表。
但是当我单击按钮时,我将数据表绑定到 gridview,并记录到 Microsoft 文档:
HTTP 是一种无状态协议。这意味着 Web 服务器将每个 对页面的 HTTP 请求作为独立请求。服务器保留 不知道之前使用的变量值 请求。
如果你有同样的条件,那么我会推荐你使用Session来保持值。
Session["oldData"]=Gridview1.DataSource;
之后您可以在页面再次回发时调用该值。
DataTable dt=(DataTable)Session["oldData"];
参考资料: 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();
【讨论】: