Click here to Skip to main content
15,868,164 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
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

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

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

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

2) apply for loop on gridview rows and add repective datarow in datatable
C#
for(int i=0;i<gridview.rowc.count;i++)>
{
DataRow dr =dt.NewRow();
dr["col1"]= gridview.rows[i]["col1"].text;
dt.rows.add(dr);
}
 
Share this answer
 
i got it ......
DataTable dt = new DataTable();


    DataSourceSelectArguments args = new DataSourceSelectArguments();

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

    dt = dv.ToTable();
 
Share this answer
 
BindingSource bs = (BindingSource )grid.DataSource;

DataTable dt = (DataTable ) bs.DataSource;

Sorry, BindingSource is only available on Windows Forms.

You can try:

C#
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
 
Share this answer
 
v2
Comments
vaibhav mahajan 20-Nov-12 7:09am    
namespace?
Why you are casting like that directly give sqldatasource1 to dt (here you need to convert datasource to datatable).
 
Share this answer
 
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900