Convert the data in grilview to a able

Source: Internet
Author: User

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;
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.