Retrieving Values of Cached Items

Retrieving data from the Cache is simple; you only need to specify the key and value that represent the data. You then write code to display the data on your page.

To retrieve the value of a cached item

  • The following code creates a Source DataView object, attempts to retrieve cached data that is assigned a key of MyData1, and assigns that data to Source. It then verifies that the data was still stored in the Cache and assigns Source as the DataSource property of a DataGrid Web server control named MyDataGrid. It then binds the data to MyDataGrid.

    DataView Source;
    Source = (DataView)Cache["MyData1"];
    
    if(Source != null ) {
      MyDataGrid.DataSource = Source;
      MyDataGrid.DataBind();
    }
    [VisualĀ Basic]
    Dim Source As DataView
    Source = CType(Cache("MyData1"), DataView)
    If Not (Source Is Nothing) Then
       MyDataGrid.DataSource = Source
       MyDataGrid.DataBind()
    End If 
    

To check for the existence of an item in the Cache

  • A more complex situation is how your application responds when a data source or data set is not in the Cache. The following example modifies the code in the previous procedure to check for the cached data. If it is not in the cache, the example recreates it and adds it to the Cache.

    DataView Source = (DataView)Cache["MyData1"];
    if (Source == null) {
       SqlConnection myConnection = new SqlConnection("server=localhost;Integrated Security=SSPI;database=pubs");
       SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);
    
       DataSet ds = new DataSet();
       myCommand.Fill(ds, "Authors");
    
       Source = new DataView(ds.Tables["Authors"]);
       Cache["MyData1"] = Source;
    }
    MyDataGrid.DataSource=Source;
    MyDataGrid.DataBind();
    [VisualĀ Basic]
    Dim Source As DataView = CType(Cache("MyData1"), DataView)
    If Source Is Nothing Then
       Dim myConnection As New SqlConnection("server=localhost;Integrated Security=SSPI;database=pubs")
       Dim myCommand As New SqlDataAdapter("select * from Authors", myConnection)
    
       Dim ds As New DataSet()
       myCommand.Fill(ds, "Authors")
    
       Source = New DataView(ds.Tables("Authors"))
       Cache("MyData1") = Source
    End If
    MyDataGrid.DataSource = Source
    MyDataGrid.DataBind()
    

See Also

Caching Application Data | Adding Items to the Cache | Deleting Items from the Cache | Notifying Applications When an Item Is Deleted from the Cache