Question

I am using a gridview with sqldatasource. How to get back the datasource in the codebehind as a datatable?

Was it helpful?

Solution

Edited

Use SqlDataSource.Select Method and assign it to a dataview

DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);

Then extract the datatable using

DataTable dt =  (DataTable)dv.ToTable();

OTHER TIPS

Use System.Data.DataTable dt = (System.Data.DataTable)gview.DataSource; if you are binding a DataTable.

You can even extract the DataTable out of DataSet if you are binding DataSet as System.Data.DataTable dt2 = (System.Data.DataTable)((System.Data.DataSet)gvValidDA.DataSource).Tables[0]; you will have to check the index of your table or table name as you prefer.

Happy coding.

The actual data is not stored in the Gridview properties as the above answers pertain.

Using direct casting to the Gridview.DataSource is not enough, as it's actually NULL when the gridview has rendered!

You have to either reload the data directly from the SQL datasource...

        DataSourceSelectArguments dss = new DataSourceSelectArguments();
        DataView dvS = sdsADDorREMstudentData.Select(dss) as DataView;
        DataTable dtS = dvS.ToTable() as DataTable;
        if (dtS != null)
        {
          ... etc...
        }

Or you can use the ViewState to retain the data before the Gridview has rendered.

    DataView dvClasses = (DataView)sdsClasses.Select(DataSourceSelectArguments.Empty);

    gvStudents.DataSourceID = "sdsClasses";
    gvStudents.DataSource = null; // Null out the source, as we have a SourceID instead
    gvStudents.DataBind();

    //save the data in a viewstate for later use (to control adding and removing students, without doing a postback! See ADD & REM methods below)
    DataView dv = (DataView)dvClasses;
    DataTable dt = new DataTable();
    if (dv != null)
    {
        dt = dv.ToTable();
        ViewState["gv"] = dt;
    }

And use the ViewState to turn it back into a DataTable, when you need to use the data AFTER the Gridview has rendered...

DataTable dt = (DataTable)ViewState["gv"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top