Click here to Skip to main content
14,175,754 members
Rate this:
 
Please Sign up or sign in to vote.
Hello everyone..!!
I have a gridview which is databinded by datasource.
i want to convert that datasource's content into datatable.

i tried this

GridView grd = new GridView();
        grd.DataSource = SqlDataSource1;
        grd.DataBind();

        DataTable dt = new DataTable();
       dt =(DataTable)grd.DataSource;


but its not working..!!

any suggestion/links are welcomed..!!
Posted
Updated 7-Aug-18 2:35am
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 4

if all this is not working then use the most Cost consuming method:

1) create a datatable and add columns as in gridview
DataTable dt = new DataTable();

dt.Columns.Add("col1");.....

2) apply for loop on gridview rows and add repective datarow in datatable
for(int i=0;i<gridview.rowc.count;i++)>
{
DataRow dr =dt.NewRow();
dr["col1"]= gridview.rows[i]["col1"].text;
dt.rows.add(dr);
}
   
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 5

i got it ......
DataTable dt = new DataTable();


    DataSourceSelectArguments args = new DataSourceSelectArguments();

    DataView dv = new DataView();
    dv = (DataView)SqlDataSource1.Select(args);

    dt = dv.ToTable();
   
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

BindingSource bs = (BindingSource )grid.DataSource;

DataTable dt = (DataTable ) bs.DataSource;

Sorry, BindingSource is only available on Windows Forms.

You can try:

bool firstTime = true;
    System.Data.DataTable dt;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
            if (this.firstTime)
            {
                System.Data.DataView dv =
                     (e.Row.DataItem as System.Data.DataRowView).DataView;
                this.dt = dv.ToTable();
                this.Label1.Text = dt.Rows.Count.ToString();
                this.firstTime = false;
            }
    }


Reference
   
v2
Comments
vaibhav mahajan 20-Nov-12 7:09am
   
namespace?
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Why you are casting like that directly give sqldatasource1 to dt (here you need to convert datasource to datatable).
   
Comments
vaibhav mahajan 20-Nov-12 7:12am
   
its not happening..!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web06 | 2.8.190525.1 | Last Updated 7 Aug 2018
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100