2012年6月10日 星期日

ASP.NET ListView 抓取EmptyDataTemplate控制項

如果你從來沒用過Asp.net ListView,而現在你是第一次用的人,必須要知道一件事,當沒有資料時ListView並不會跑ItemDataBound事件中的ListViewItemType.EmptyItem,而GridView它是沒有資料時也會跑ItemDataBound事件中的ListViewItemType.EmptyItem。

以下就是當ListView 沒有資料時,如何抓取EmptyDataTemplate控制項,並顯示訊息...

前端:


<asp:ListView ID="ListView1" runat="server" DataKeyNames="id">
....
  <EmptyDataTemplate>
    <asp:Label ID="LVEmpty" runat="server" ></asp:Label>
  </EmptyDataTemplate>
....
</asp:ListView>

------------------------------

後置程式碼:

....
ListView1.DataSource = Nothing
'當無資料時,跑過以下這行DataBind,也不會進入ItemDataBound事件
ListView1.DataBind()
'Controls(0)是指ListView1中的EmptyDataTemplate, FindControl 抓取控制項LVEmpty
Dim LV_Empty As Label = CType( ListView1.Controls(0).FindControl(" LVEmpty "), Label)
LV_Empty.Text="無資料"
....


以上是比較簡單的方法,如果有更好的方法請提出建議,感謝~

參考資料:http://www.dotblogs.com.tw/hatelove/archive/2010/11/19/listview-emptydatatemplate-findcontrol.aspx