Asp.Net静的メソッドのGrid回転DataTableメソッド実装手順

4360 ワード

GridViewバインドDataTable後、GridViewバインド後に表示される値をどのように取得するかは、プロジェクトのニーズを背景に、セル表示テキストを取得する方法を検索し、静的な方法を書き、プロジェクトでの使用を経て、バグの修復を経て、安定しています.
独楽は衆楽楽に及ばず、コードを貼ってみんなの指摘に供する.
 
  
#region ================GridView DataTable ================
/// GridView DataTable : http://www.qqextra.com,http://blog.csdn.net/ls_man
/// GridView
///
/// DataTable
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++;
}
}
}
}// : http://www.qqextra.com,http://blog.csdn.net/ls_man
//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;
}
/// GridView DataTable : http://www.qqextra.com,http://blog.csdn.net/ls_man
/// GridView
/// GridView
///
/// DataTable
public static DataTable GridViewToDataTable(GridView gv, DataTable dtSource, Boolean showHideColumn)
{
// GridView
gv.DataSource = dtSource;
gv.DataBind();
//
gv.AllowPaging = false;// : http://www.qqextra.com,http://blog.csdn.net/ls_man
//GridView DataTable
return GridViewToDataTable(gv, showHideColumn);
}
#endregion
#region ================ ================
/// TableCell : http://www.qqextra.com,http://blog.csdn.net/ls_man
/// TableCell
/// string
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
", "").Trim();
continue;
} : http://www.qqextra.com,http://blog.csdn.net/ls_man
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
", "").Trim();
continue;
}
}
//
return cellText;
}
#endregion