4.5 Encapsulation
The encapsulation code of the class is as follows:
Using system. Data;
Using system. Web. UI. webcontrols;
/// <Summary>
/// When the data record bound to the gridview is empty, the header of the gridview is displayed, and no record is displayed.
/// </Summary>
Public class gridviewcontrol
{
// Information displayed when the gridview data is empty
Private Static string emptytext = "no record ";
Public gridviewcontrol ()
{
}
/// <Summary>
/// Prevent the gridview from being displayed after PostBack
/// </Summary>
/// <Param name = "gridview"> </param>
Public static void resetgridview (gridview)
{
// Re-construct the gridview if the data is null
If (gridview. Rows. Count = 1 & gridview. Rows [0]. cells [0]. Text = emptytext)
{
Int columncount = gridview. Columns. count;
Gridview. Rows [0]. cells. Clear ();
Gridview. Rows [0]. cells. Add (New tablecell ());
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 the data to the gridview. When the table data is empty, the header is displayed.
/// </Summary>
/// <Param name = "gridview"> </param>
/// <Param name = "table"> </param>
Public static void gridviewdatabind (gridview, datatable table)
{
// Record is empty to reconstruct the gridview
If (table. Rows. Count = 0)
{
Table = table. Clone ();
Table. Rows. Add (table. newrow ());
Gridview. datasource = table;
Gridview. databind ();
Int columncount = table. Columns. count;
Gridview. Rows [0]. cells. Clear ();
Gridview. Rows [0]. cells. Add (New tablecell ());
Gridview. Rows [0]. cells [0]. columnspan = columncount;
Gridview. Rows [0]. cells [0]. Text = emptytext;
Gridview. Rows [0]. cells [0]. style. Add ("text-align", "center ");
}
Else
{
// Bind directly if the data is not empty
Gridview. datasource = table;
Gridview. databind ();
}
// Unbind and unselect
Gridview. selectedindex =-1;
}
}
You can compile this class into DLL for calling in various places.
4.6 example
The usage of this class is very simple, that is, every time you bind data, gridviewdatabind is called. The first parameter of this function is the gridview parameter to bind data. The second parameter is the datatable that contains the data field column, it may be null or not empty. If the data is not empty, the function is automatically bound normally. Otherwise, the "no record" prompt is displayed.
The code for the above button event can be changed to the following:
Datatable dt = new datatable ();
DT. Columns. Add ("temple_id ");
DT. Columns. Add ("temple_name ");
DT. Columns. Add ("location ");
DT. Columns. Add ("build_date ");
Gridviewcontrol. gridviewdatabind (this. gridviewemptydatatest, DT );
Finally, in page_load, The resetgridview function is called for all the gridview functions on this page, as shown below:
If (ispostback)
{
Gridviewcontrol. resetgridview (this. gridviewemptydatatest );
}