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

Pen*_*uen 40 c# asp.net gridview

如何导出GridView.DataSource到数据表或数据集?

Kon*_*Kon 48

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

myGridView.DataSource as DataTable
Run Code Online (Sandbox Code Playgroud)

  • 那你呢**接受**的答案?! (23认同)

小智 28

你应该先转换DataSourceBindingSource,例如看

BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource 
DataTable tCxC = (DataTable) bs.DataSource;
Run Code Online (Sandbox Code Playgroud)

有了tCxC你的数据,你可以做任何事情.


Tac*_*667 19

就我个人而言:

DataTable tbl = Gridview1.DataSource as DataTable;
Run Code Online (Sandbox Code Playgroud)

这将允许您测试null,因为这会导致DataTable对象或null.如果DataSource实际上是DataSet甚至某种集合,使用(DataTable)Gridview1.DataSource将其作为DataTable进行转换会导致崩溃错误.

支持文档:关于"as"的MSDN文档

  • 虽然这没有产生任何错误,但当我悬停检查我的数据表的值时,即使我的gridview显示填充数据,它也会显示为null.DataTable dt = gvJobSearchEngine.DataSource as DataTable; (2认同)

小智 8

安布,

我和你有同样的问题,这是我用来解决它的代码.虽然,我没有使用页脚行部分用于我的目的,但我确实将它包含在此代码中.

    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);
    }
Run Code Online (Sandbox Code Playgroud)