在webform开发中难免会遇到将GrilView中的数据转换成DataTable,下面的类将实现这个功能,但仅是显示出来的数据,如有分页得另行处理。
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI;
public class GridViewHelper
{
//从GridView的数据生成DataTable
public static DataTable GridViewToDataTable(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)
{
DataColumn dc = table.Columns.Add();
string columnName = cols[i];
if (String.IsNullOrEmpty(columnName))
{
columnName = gv.Columns[i].HeaderText;
if (string.IsNullOrEmpty(columnName))
{
continue;
}
}
dc.ColumnName = columnName;
dc.DataType = typeof(string);
}
row[j] = text;
}
j++;
}
rowIndex++;
table.Rows.Add(row);
}
}
return table;
}
public static string GetCellText(TableCell cell)
{
string text = cell.Text;
if (!string.IsNullOrEmpty(text))
{
return text;
}
foreach (Control control in cell.Controls)
{
if (control != null && control is ITextControl)
{
LiteralControl lc = control as LiteralControl;
if (lc != null)
{
continue;
}
ITextControl l = control as ITextControl;
text = l.Text.Replace("\r\n", "").Trim();
break;
}
}
return text;
}
}