如何讓Gridview在沒有數據的時候顯示表頭(asp.net)


1.前言

當對GridView控件進行數據綁定時,如果綁定的記錄為空,網頁上就不顯示GridView,造成頁面部分空白,頁面布局結構也受影響。下面討論的方法可以讓GridView在沒有數據記錄的時候顯示表的字段結構和顯示提示信息。

2.數據

為了讓GridView顯示數據,在數據庫中建立表temple,其字段如下:

temple表示廟宇,它的字段有:

temple_id       int

temple_name   varchar(50)

location   varchar(50)

build_date       datetime

 

temple的數據為:

temple_id

temple_name

location

build_time

1

少林寺

河南省登封市嵩山

1900-2-2 0:00:00

2

大傑寺

五龍山

1933-2-3 3:03:03

3

法源寺

宣武門外教子胡同南端東側

1941-2-3 5:04:03

4

廣濟寺

阜成門內大街東口

1950-3-3 3:03:03

5

碧雲寺

香山東麓

1963-3-3 3:03:03

 

3.頁面

建立一個asp.net網站工程,在頁面中添加GridView和幾個按鈕,代碼如下所示:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>GridView綁定記錄為空顯示表頭測試</title>

</head>

<body>

    <form id="form1" runat="server">

    <div style="font-size:13px;">

    <asp:GridView ID="GridViewEmptyDataTest" runat="server" AutoGenerateColumns="False" EmptyDataText="Data Is Empty" BackColor="White" BorderColor="LightGray" BorderStyle="Double" BorderWidth="3px"

          CellPadding="4" GridLines="Horizontal" Width="500px">

            <Columns>

                <asp:BoundField DataField="temple_id" HeaderText="temple_id" Visible="False" >

                </asp:BoundField>

                <asp:BoundField DataField="temple_name" HeaderText="名稱" >

                    <ItemStyle BorderColor="LightGray" BorderStyle="Double" BorderWidth="1px" Width="100px" />

                </asp:BoundField>

                <asp:BoundField DataField="location" HeaderText="地址" >

                    <ItemStyle BorderColor="LightGray" BorderStyle="Double" BorderWidth="1px" Width="300px" />

                </asp:BoundField>

                <asp:BoundField DataField="build_date" HeaderText="建設時間" >

                    <ItemStyle BorderColor="LightGray" BorderStyle="Double" BorderWidth="1px" Width="100px" />

                </asp:BoundField>

            </Columns>

            <FooterStyle BackColor="White" ForeColor="#333333" />

            <RowStyle BackColor="White" ForeColor="#333333" />

            <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />

            <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />

            <HeaderStyle BackColor="CornflowerBlue" Font-Bold="True" ForeColor="White" />

        </asp:GridView>

        <br />

        <asp:Button ID="ButtonHasDataBind" runat="server" Text="有數據綁定" Width="109px" OnClick="ButtonHasDataBind_Click" />

        <asp:Button ID="ButtonQueryEmptyBind" runat="server" Text="查詢結果為空綁定" Width="142px" OnClick="ButtonQueryEmptyBind_Click" />

        <asp:Button ID="ButtonConstructTableBind" runat="server" Text="構造空的DataTable綁定" Width="164px" OnClick="ButtonConstructTableBind_Click" />

        <asp:Button ID="ButtonNormalBind" runat="server" Text="普通空數據綁定" Width="127px" OnClick="ButtonNormalBind_Click" /></div>

    </form>

</body>

</html>

GridView要綁定的字段和temple的字段一樣,在這里我們利用GridView原有的功能,設定當數據為空是顯示“Data Is Empty”,如果沒有設定EmptyDataText屬性,當綁定的記錄為空時,GridView將不在頁面顯示。

4.數據顯示

4.1普通空記錄顯示

編寫ButtonNormalBind的事件函數ButtonNormalBind_Click,添加如下代碼,來測試沒有經過處理的GridView顯示情況:

protected void ButtonNormalBind_Click(object sender, EventArgs e)

    {

        DataTable dt = new DataTable();

 

        dt.Columns.Add("temple_id");

        dt.Columns.Add("temple_name");

        dt.Columns.Add("location");

        dt.Columns.Add("build_date");

 

        this.GridViewEmptyDataTest.DataSource = dt;

        this.GridViewEmptyDataTest.DataBind();

}

執行這些代碼后,GridView顯示結果如下圖所示:

可以看到這樣簡單的提示看不出GridView的結構來,在大多數的實際應用中我們希望看到GridView到底有哪些字段。

4.2增加空行來顯示GridView的結構

我們知道只要GridView綁定的DataTable有一行記錄,GridView就會顯示表頭,所以當DataTable為空時我們增加一個空行從而顯示表頭。

我們把代碼改成如下所示:

DataTable dt = new DataTable();

 

        dt.Columns.Add("temple_id");

        dt.Columns.Add("temple_name");

        dt.Columns.Add("location");

        dt.Columns.Add("build_date");

 

        if (dt.Rows.Count == 0)

        {

            dt.Rows.Add(dt.NewRow());

        }

 

        this.GridViewEmptyDataTest.DataSource = dt;

    this.GridViewEmptyDataTest.DataBind();

在每次綁定前判斷,如果為空就增加一空行,這樣綁定的結果如下圖所示:

可以看得表頭已經可以顯示了,但是顯示的空行沒有任何數據也讓人費解,可不可以增加一下提示信息呢?

4.3增加空記錄提示

我們在數據綁定后增加一些代碼對GridView進行一下處理,讓顯示結果更友好。在this.GridViewEmptyDataTest.DataBind();后面增加代碼如下所示:

int columnCount = dt.Columns.Count;

        GridViewEmptyDataTest.Rows[0].Cells.Clear();

        GridViewEmptyDataTest.Rows[0].Cells.Add(new TableCell());

        GridViewEmptyDataTest.Rows[0].Cells[0].ColumnSpan = columnCount;

        GridViewEmptyDataTest.Rows[0].Cells[0].Text = "沒有記錄";

     GridViewEmptyDataTest.Rows[0].Cells[0].Style.Add("text-align", "center");
 GridViewEmptyDataTest.Rows[0].Cells[0].Style.Add("color", "red");

改良后的顯示結果如下圖所示:

看來顯示結果已經達到了我們的要求,但是當頁面上有其他按鈕操作導致頁面PostBack時,頁面再次顯示確沒有了提示信息變成如下圖所示的樣子:

這並不是我們想要的。

4.4防止PostBack時頁面顯示變化

為了防止顯示改變我們在Page_Load事件里添加如下代碼,從而重新綁定GridView:

if (IsPostBack)

        {

            //如果數據為空則重新構造Gridview

            if (GridViewEmptyDataTest.Rows.Count == 1 && GridViewEmptyDataTest.Rows[0].Cells[0].Text == "沒有記錄")

            {

                int columnCount = GridViewEmptyDataTest.Columns.Count;

                GridViewEmptyDataTest.Rows[0].Cells.Clear();

                GridViewEmptyDataTest.Rows[0].Cells.Add(new TableCell());

                GridViewEmptyDataTest.Rows[0].Cells[0].ColumnSpan = columnCount;

                GridViewEmptyDataTest.Rows[0].Cells[0].Text = "沒有記錄";

                GridViewEmptyDataTest.Rows[0].Cells[0].Style.Add("text-align", "center");
                 GridViewEmptyDataTest.Rows[0].Cells[0].Style.Add("color", "red");
            }

   }

這下我們的控件終於可以按我們的要求顯示了,但是為了代碼的重用,當一個項目里有多個GridView時,避免充分些相同的代碼,我們需要把代碼封裝成類,從而讓所有的GridView數據綁定時都可以輕易地實現我們的要求。

4.5封裝

類的封裝代碼如下所示:

using System.Data;

using System.Web.UI.WebControls;

 

/// <summary>

/// Gridview綁定的數據記錄為空時顯示Gridview的表頭,並顯示沒有記錄的提示

/// </summary>

public class GridviewControl

{

    //當Gridview數據為空時顯示的信息

    private static string EmptyText = "沒有記錄";

 

     public GridviewControl()

     {

        

     }

 

    /// <summary>

    /// 防止PostBack后Gridview不能顯示

    /// </summary>

    /// <param name="gridview"></param>

    public static void ResetGridView(GridView gridview)

    {

        //如果數據為空則重新構造Gridview

        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");
            gridview.Rows[0].Cells[0].Style.Add("color", "red");
        }

    }

 

    /// <summary>

    /// 綁定數據到GridView,當表格數據為空時顯示表頭

    /// </summary>

    /// <param name="gridview"></param>

    /// <param name="table"></param>

    public static void GridViewDataBind(GridView gridview, DataTable table)

    {

        //記錄為空重新構造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");
             gridview.Rows[0].Cells[0].Style.Add("color", "red");
        }

        else

        {

            //數據不為空直接綁定

            gridview.DataSource = table;

            gridview.DataBind();

        }

 

        //重新綁定取消選擇

        gridview.SelectedIndex = -1;

    }

}

你可以把這個類編譯成DLL,讓各個地方調用。

4.6使用示例

這個類的使用很簡單,就是在每次進行數據綁定是調用GridViewDataBind,這個函數的第一個參數是要綁定數據的GridView第二個參數是包含數據字段列的DataTable,可能為空可能不空,如果數據不空,函數則自動進行正常綁定,否則顯示“沒有記錄”的提示。

上面的按鈕事件的代碼可以改成如下所示:

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

最后在Page_Load中對本頁面所有GridView調用ResetGridView函數,如下所示:

if (IsPostBack)

        {

            GridviewControl.ResetGridView(this.GridViewEmptyDataTest);

    }

 

(PS: 轉至:http://blog.csdn.net/zhyuanshan/article/details/1815899


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM