直接上方法:
/// <summary>
/// 从GridView的数据生成DataTable
/// </summary>
/// <param name="gv">GridView对象</param>
public static DataTable GridView2DataTable(GridView gv)
{
DataTable table = new DataTable();
int rowIndex = 0;
List<string> cols = new List<string>();
if (!gv.ShowHeader && gv.Columns.Count == 0)
{
return table;
}
GridViewRow headerRow = gv.HeaderRow;
int columnCount = headerRow.Cells.Count;
for (int i = 0; i < columnCount; i++)
{
string text = GetCellText(headerRow.Cells[i]);
cols.Add(text);
}
foreach (GridViewRow r in gv.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
DataRow row = table.NewRow();
int j = 0;
for (int i = 0; i < columnCount; i++)
{
string text = GetCellText(r.Cells[i]);
if (!String.IsNullOrEmpty(text))
{
if (rowIndex == 0)
{
string columnName = cols[i];
if (String.IsNullOrEmpty(columnName))
{
continue;
}
if (table.Columns.Contains(columnName))
{
continue;
}
DataColumn dc = table.Columns.Add();
dc.ColumnName = columnName;
dc.DataType = typeof(string);
}
row[j] = text;
j++;
}
}
rowIndex++;
table.Rows.Add(row);
}
}
return table;
}