如何将GridView.DataSource导出到datatable或dataset?

42

我该如何将GridView.DataSource导出到数据表或数据集中?


3
GridView.DataSource所指向的对象属于哪种类型? - Mitch Wheat
http://www.vbforums.com/showthread.php?t=474895 - TheTXI
7个回答

50

假设您的DataSource是DataTable类型,您可以直接这样做:

myGridView.DataSource as DataTable

这是这个问题的最佳答案,谢谢。 - MBH
1
我设置了 datagridview.DataSource = dataTable,但是当我想通过这种方式从 DataSource 中读取时,会抛出无效转换异常,错误信息为:无法将类型为 'System.Windows.Forms.BindingSource' 的对象强制转换为类型 'System.Data.DataTable'。 - Behzad

27

你应该将 DataSource 先转换为 BindingSource,参考示例

BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource 
DataTable tCxC = (DataTable) bs.DataSource;

拥有tCxC的数据,你可以做任何事情。


19

个人而言,我会选择:

DataTable tbl = Gridview1.DataSource as DataTable;

这将使您能够测试空值,因为结果可能是DataTable对象或null。使用(DataTable)Gridview1.DataSource 将其转换为DataTable会导致崩溃错误,如果DataSource实际上是DataSet甚至某种集合。

支持文档:MSDN“as”的文档


3
尽管这没有产生任何错误,但当我悬停以检查我的数据表的值时,它显示为空,即使我的GridView显示已经填充了数据。 DataTable dt = gvJobSearchEngine.DataSource as DataTable; - John Waclawski

8

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("&nbsp;","");
        }
        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("&nbsp;","");
        }
        dt.Rows.Add(dr);
    }

2

如果您在以下位置执行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/


@John Waclawski 我和你一样遇到了同样的问题。我找到了这个解决方案,希望能对你有所帮助。 - 劉鎮瑲

1

我使用了下面这行代码,它有效,请尝试

DataTable dt =  dataSource.Tables[0];

0

虽然有点晚,但这很有帮助。我只是为了以后参考而发布。

DataTable dt = new DataTable();
Data.DataView dv = default(Data.DataView);
dv = (Data.DataView)ds.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();

当我尝试你的代码时,Data.DataView没有任何智能感知弹出窗口。 - John Waclawski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接