复制代码 代码如下:
#region ================GridView转DataTable方法================
/// <summary>GridView转DataTable 版权:求知域,转载请注明出处</summary>
/// <param>已绑定数据源的GridView</param>
/// <param>是否显示隐藏列</param>
/// <returns>DataTable</returns>
public static DataTable GridViewToDataTable(GridView gv, Boolean showHideColumn)
{
//处理后的数据表
DataTable dt = new DataTable();
//记录符合条件索引
int[] columnIndexs = new int[gv.HeaderRow.Cells.Count];
//记录指示器从0开始
int columnIndexsCount = 0;
//初始化dt列名
for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
{
//获取列名
string columnName = GetCellText(gv.HeaderRow.Cells[i]);
//string columnName = gv.HeaderRow.Cells[i].Text;
//列名非空//且可见
if (!string.IsNullOrEmpty(columnName))
{
//是否显示隐藏列
if (gv.HeaderRow.Cells[i].Visible || showHideColumn)
{
//列名不允许重复
if (!dt.Columns.Contains(columnName))
{
//dt中新增一列
DataColumn dc = dt.Columns.Add();
//列名
dc.ColumnName = columnName;
//存储的数据类型
dc.DataType = typeof(string);
//记录符合条件的列索引
columnIndexs[columnIndexsCount] = i;
//记录指示器+1
columnIndexsCount++;
}
}
}
}//版权:求知域,转载请注明出处
//GridView行复制到数组中便于操作
GridViewRow[] allGridViewRow = new GridViewRow[gv.Rows.Count];
gv.Rows.CopyTo(allGridViewRow, 0);
//数据添加到dt中
foreach (GridViewRow row in allGridViewRow)
{
//创建一行
DataRow dr = dt.NewRow();
//符合条件的列
for (int i = 0; i < columnIndexsCount; i++)
{
//获取显示文本并保存
dr[i] = GetCellText(row.Cells[columnIndexs[i]]);
}
//dt中增加此行
dt.Rows.Add(dr);
}
//返回处理后的数据
return dt;
}
/// <summary>GridView转DataTable 版权:求知域,转载请注明出处</summary>
/// <param>未绑定数据源的GridView</param>
/// <param>GridView的数据源</param>
/// <param>是否显示隐藏列</param>
/// <returns>DataTable</returns>
public static DataTable GridViewToDataTable(GridView gv, DataTable dtSource, Boolean showHideColumn)
{
//绑定原始数据到GridView
gv.DataSource = dtSource;
gv.DataBind();
//设置为不分页
gv.AllowPaging = false;<SPAN>//版权:求知域,转载请注明出处
//GridView转DataTable并返回
return GridViewToDataTable(gv, showHideColumn);
}
#endregion
#region ================私有工具方法================
/// <summary>获取TableCell的显示文本 版权:求知域,转载请注明出处</summary>
/// <param>TableCell</param>
/// <returns>string</returns>
private static string GetCellText(TableCell cell)
{
string cellText = cell.Text;
//常规文本(无控件)直接返回
if (!string.IsNullOrEmpty(cellText))
{
//返回显示文本
return cellText.Replace(" ", "");
}
//遍历cell中的控件
foreach (Control control in cell.Controls)
{
if (control != null && control is IButtonControl)
{
IButtonControl btn = control as IButtonControl;
cellText += btn.Text.Replace("/r/n", "").Trim();
continue;
}版权:求知域,转载请注明出处
if (control != null && control is ITextControl)
{
LiteralControl lc = control as LiteralControl;
if (lc != null)
{
//跳出到下一步foreach
continue;
}
ITextControl l = control as ITextControl;
cellText += l.Text.Replace("/r/n", "").Trim();
continue;
}
}
//返回显示文本
return cellText;
}
#endregion
</SPAN>
新闻热点
疑难解答
图片精选