2009-07-30 73 views
0

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

任何想法如何做到这一点整齐?

回答

1

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

<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> 
0

你可以使用这个小功能:

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