How can I export a GridView.DataSource to a datatable or dataset?

后端 未结 7 1121
心在旅途
心在旅途 2020-11-28 08:45

How can I export GridView.DataSource to datatable or dataset?

相关标签:
7条回答
  • 2020-11-28 08:55

    Ambu,

    I was having the same issue as you, and this is the code I used to figure it out. Although, I don't use the footer row section for my purposes, I did include it in this code.

        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);
        }
    
    0 讨论(0)
  • 2020-11-28 08:59

    Personally I would go with:

    DataTable tbl = Gridview1.DataSource as DataTable;
    

    This would allow you to test for null as this results in either DataTable object or null. Casting it as a DataTable using (DataTable)Gridview1.DataSource would cause a crashing error in case the DataSource is actually a DataSet or even some kind of collection.

    Supporting Documentation: MSDN Documentation on "as"

    0 讨论(0)
  • 2020-11-28 09:01

    Assuming your DataSource is of type DataTable, you can just do this:

    myGridView.DataSource as DataTable
    
    0 讨论(0)
  • 2020-11-28 09:03

    This comes in late but was quite helpful. I am Just posting for future reference

    DataTable dt = new DataTable();
    Data.DataView dv = default(Data.DataView);
    dv = (Data.DataView)ds.Select(DataSourceSelectArguments.Empty);
    dt = dv.ToTable();
    
    0 讨论(0)
  • 2020-11-28 09:06

    You should convert first DataSource in BindingSource, look example

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

    With the data of tCxC you can do anything.

    0 讨论(0)
  • 2020-11-28 09:07

    I have used below line of code and it works, Try this

    DataTable dt =  dataSource.Tables[0];
    
    0 讨论(0)
提交回复
热议问题