2014-01-19 81 views
0

我有一個列表視圖在我的asp.net頁面綁定到一個數據表,這是從後面的代碼完成頁面加載。我正在嘗試使用SelectedItemTemplate,但是從反覆試驗來看,如果控件在回發之後發生數據綁定,我只能得到它。這工作正常,但問題是這意味着每次都會回調數據庫,即使沒有數據更改,這也會讓用戶體驗變慢。因此,我的問題是:是否可以在列表視圖上選擇一個項目,並顯示SelectedItemTemplate,而無需對數據進行完全重新綁定。我不介意回發到服務器,我只是想避免對數據庫進行不必要的調用。這裏是我的標記:asp.net listview select item without databind

<asp:ListView ID="lv" runat="server" DataKeyNames="id" EnablePersistedSelection="True"> 
    <LayoutTemplate> 
     <ul> 
      <li runat="server" id="itemPlaceholder"></li> 
     </ul> 
    </LayoutTemplate> 
    <ItemTemplate> 
     <div id="Div1" runat="server"> 
      <!-- My Item Controls --> 
     </div> 
    </ItemTemplate> 
    <SelectedItemTemplate> 
     <div id="Div2" runat="server"> 
      <!-- My Selected Item Controls --> 
     </div> 
    </SelectedItemTemplate> 
</asp:ListView> 

這裏是我的代碼隱藏:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    If Not IsPostBack Then 
     'Load the data on the first page load 
     LoadEvents() 
    End If 
End Sub 

Protected Sub LoadEvents() 
    'Some code to get data from DB and bind to listview control 
End Sub 

Protected Sub lv_SelectedIndexChanging(sender As Object, e As ListViewSelectEventArgs) Handles lv.SelectedIndexChanging 
    lv.SelectedIndex = e.NewSelectedIndex 
    LoadEvents() 
End Sub 

提前感謝!

回答

0

您可以將DataTable保存在Session中,然後在LoadEvents中檢索它。僅在初始加載時,它將來自DataBase。該LoadEvents子可能是這樣的:

Private Sub LoadEvents(Optional ByVal refresh As Boolean = False) 
    Dim myTable As DataTable = New DataTable 
    If refresh = True Then 
     'Code to get data from database 
     'and fill myTable Goes here 
     ' ... ... ... 

     Session("MyTable") = myTable 
    Else 
     If Not Session("MyTable") Is Nothing Then 
      myTable = DirectCast(Session("MyTable"), DataTable) 
     End If 
    End If 

    lv.DataSource = myTable 
    lv.DataBind() 
End Sub 

當它被稱爲不帶參數,它將從會議獲得的數據。在Page_Load我們需要true調用它從數據庫中獲取新的數據:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    If Not IsPostBack Then 
      'Load the data on the first page load 
      'Called the sub with parameter to get fresh data from db 
      LoadEvents(true) 
    End If 
End Sub 
+0

謝謝,這真是棒極了! – Richwrx