[RESOLVED] GridView to DataTable
Is there an easy way to pass data from a GridView to a DataTable,..??
I have a loaded GridView,....
Code:
DataTable dt = new DataTable();
foreach (GridViewRow dr in GridView1.Rows)
{
DataRow testDr = (dataRow)dr ,.... I tried this and it didn“t work,.
}
Thanks,
Re: GridView to DataTable
It may vary depending upon the DataSource of your GridView.
Try
C# Code:
//If DataSource of GridView1 is a DataTable
DataTable dt = (DataTable)GridView1.DataSource;
//If DataSource of GridView1 is a DataView
DataView dv = (DataView)GridView1.DataSource;
In your code, you cannot convert GridViewRow to DataRow. You have to manually create columns first, then loop through all the rows. Within this loop, you would need to loop through all the columns of the row and copy it to the DataRow that you are creating.
c# Code:
//This is just a Psuedocode
DataTable dt = new DataTable();
//Add columns here
dt.Columns.Add(); //or something similar
//go on till all the columns are added
//loop and second loop
foreach(GridViewRow gvr in GridView1.Rows)
{
DataRow dr = dt.NewRow();
//second loop - looping all columns
for(int i = 0; i < gvr.Rows.Count; ++i)
{
dr[i] = gvr.Cells[i].Text;
}
}
Hope it helps you.
Re: GridView to DataTable