In webform development, it is inevitable that the data in grilview will be converted to a able. The following classes will implement this function, but only the data displayed will be processed separately.
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. Web. UI. webcontrols;
Using system. Data;
Using system. Web. UI;
Public class gridviewhelper
{
// Generate a able from the data in the gridview
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 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;
}
}