代码之家  ›  专栏  ›  技术社区  ›  RubbleFord

GridView和空数据源

  •  0
  • RubbleFord  · 技术社区  · 16 年前

    我有一个GridView,我希望它显示标题行,即使它绑定到的集合中没有任何数据。

    有什么办法可以干净利落地做到这一点吗?

    2 回复  |  直到 13 年前
        1
  •  1
  •   Russ Cam    16 年前

    使用 <EmptyDataTemplate> GridView 控件定义在数据源不包含数据时要显示的表。例如

    <EmptyDataTemplate>
        <table class="Standard" cellspacing="0" cellpadding="0">
            <tr>
                <th style="width: 25%;">
                    Header 1</th>
                <th style="width: 25%;">
                    Header 2</th>
                <th style="width: 25%;">
                    Header 3</th>
                <th style="width: 25%;">
                    Header 4`</th>
            </tr>
            <tr>
                <td style="text-align: center; font-size: 1em; font-style: italic; padding: 1em 1em 1em 1em;"
                    colspan="4">
                    --- No results found ---
                </td>
            </tr>
        </table>
    </EmptyDataTemplate>
    
        2
  •  0
  •   Misiu    13 年前

    你可以使用这个小功能:

    public static void ShowNoResultFound(DataTable source, GridView gridView)
        {
            DataTable t = source.Clone();
            foreach (DataColumn c in t.Columns)
                c.AllowDBNull = true;
            t.Rows.Add(t.NewRow());
            gridView.DataSource = t;
            gridView.DataBind();
            gridView.Rows[0].Visible = false;
            gridView.Rows[0].Controls.Clear();
        }
    

    然后,当您从SQL或其他数据源获取数据时,请执行以下操作:

    if (dSet.Tables[0].Rows.Count > 0)
    {
        GridView1.DataSource = dSet.Tables[0];
        GridView1.DataBind();
    }
    else
    {
        ShowNoResultFound(dSet.Tables[0], GridView1);
    }
    
    推荐文章