Click here to Skip to main content
12,758,605 members (35,648 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C#2.0 C#3.0 VS2008 C# ASP.NET .NET , +
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 20-Nov-12 1:59am
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);
}
  Permalink  
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
  Permalink  
v2
Comments
vaibhav mahajan 20-Nov-12 7:09am
   
namespace?
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();
  Permalink  
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).
  Permalink  
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 | Mobile
Web02 | 2.8.170217.1 | Last Updated 21 Nov 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

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