Ask for demand
The GridView control is very convenient and quick to develop in the background management, but it is troublesome to display "no data" when there is no data, and it is a cumbersome thing to implement the binding list<t> and DataTable in a public method, if no record is displayed "No data" and a table header.
Show effect
Implementation code
usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Linq;usingSystem.Reflection;usingsystem.web;usingSystem.Web.UI.WebControls;/// <summary>///Summary description of Controlextension/// </summary> Public classcontrolextension{ Publiccontrolextension () {// //TODO: Add constructor logic here// } Private Static stringEmptytext ="No record"; /// <summary> ///prevent postback after the GridView cannot be displayed/// </summary> /// <param name= "GridView" ></param> Private Static voidResetgridview (GridView GridView) {//Reconstructs The GridView if the data is empty if(GridView. Rows.Count = =1&& GridView. rows[0]. cells[0]. Text = =Emptytext) { intColumnCount =GridView. Columns.count; Initgridview (GridView, ColumnCount); } } Private Static voidInitgridview (GridView GridView,intColumnCount) {GridView. rows[0]. Cells.clear (); Gridview. rows[0]. Cells.add (NewTableCell ()); Gridview. rows[0]. cells[0]. ColumnSpan =ColumnCount; Gridview. rows[0]. cells[0]. Text =Emptytext; Gridview. rows[0]. cells[0]. Style.add ("text-align","Center"); } /// <summary> ///bind data to GridView, Show table header when table data is empty/// </summary> /// <param name= "GridView" ></param> /// <param name= "table" ></param> Public Static voidGridviewbind (GridView GridView, DataTable table) {//log empty to reconstruct GridView if(table. Rows.Count = =0) {Table=table. Clone (); Table. Rows.Add (table. NewRow ()); Gridview. DataSource=table; Gridview. DataBind (); intColumnCount =GridView. Columns.count; Initgridview (GridView, ColumnCount); } Else { //data is not directly bound to nullGridview. DataSource =table; Gridview. DataBind (); } //rebind DeselectGridview. SelectedIndex =-1; } Public Static voidGridviewbind<t> (GridView GridView, list<t>list) { //log empty to reconstruct GridView if(list. Count = =0) {DataTable table=NewDataTable (); DataRow Dr=table. NewRow (); Type type=typeof(T); foreach(PropertyInfo Pinchtype. GetProperties ()) {DataColumn DC=NewDataColumn (p.name); Table. Columns.Add (DC); } table. Rows.Add (table. NewRow ()); Gridview. DataSource=table; Gridview. DataBind (); intColumnCount =GridView. Columns.count; Initgridview (GridView, ColumnCount); } Else { //data is not directly bound to nullGridview. DataSource =list; Gridview. DataBind (); } //rebind DeselectGridview. SelectedIndex =-1; }}Calling code
Controlextension.gridviewbind<apis> (this. GridView1, list);
Extended GridView implementation without data processing