How to copy gridview content to a data table on postback
My project has a GridView to display some information. That GridView has some OnRowDataBound processing to massage the data. What I'm trying to do is copy the resulting GridView into a DataTable so I can generate a CSV file. The CSV is generated when the user clicks a button. So the GridView is on the screen and populated and a PostBack occurs. The GridView is not being re-bound on PostBack. What is the recommended way to do this? Here is the code I'm trying currently but I just end up with the headings and blank rows. Debugging confirms that row.Cells[i].Text is empty even though the heading is correct and there is the same number of rows as my GridView contained.
DataTable dataTable = new DataTable("export");
foreach (DataControlField column in myGV.Columns)
{
dataTable.Columns.Add(new DataColumn { ColumnName = column.HeaderText });
}
foreach (GridViewRow row in my开发者_如何转开发GV.Rows)
{
DataRow dataRow = dataTable.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dataRow[myGV.Columns[i].HeaderText] = row.Cells[i].Text;
}
}
You need to work with the data object you're binding to the GridView, not the gridview. There is no hook to the data in the gridview after binding.
精彩评论