Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Caching listboxes and dropdownlists? 1

Status
Not open for further replies.

song2siren

Programmer
Jun 4, 2003
103
GB
Hello

I use the following function in my code behind when the page loads to populate a listbox from values in a SQL table:

Public Function GetSubjects() As DataView
cmdSql = New SqlCommand("Pubs_getSubjects", myConnection)
cmdSql.CommandType = CommandType.StoredProcedure
myConnection.Open()
frmSubjects.DataSource = cmdSql.ExecuteReader()
frmSubjects.DataBind()
'insert blank choice on top of the subjects listbox.
frmSubjects.Items.Insert(0, New ListItem("Select Subject...", [String].Empty))
myConnection.Close()
End Function

However, I just need some guidance on how I would cache things like this rather than open a connection to the database each time the page is opened. Any suggestions would be very much appreciated.

Thanks
 
You would cache (session or cache object, depending on your usage) the data that comes from the db rather than caching the entire control. With this said, load your data into a datatable rather than using an reader object (it's forward only and good for one use).

Code:
Function GetSubjects() as DataTable

Dim dt as DataTable
Dim cacheData as DataTable = Session("MyKey")

If cacheData Is Nothing Then
  dt = .... << get your data into table (DataAdapter.Fill would work >>
  Session.Add("MyKey",dt)
  Return dt
Else
  Return cache
End If

End Function

....Now you can use the GetSubjects() as a data source to whatever you need.

....Keep in mind that you want to open and close a connection to the database each time you need it; let garbage collection handle the disposing of the connection objects after closing; also this will prevent too many connections opening simultaneously, besides, it's good programming practice.

regards,
Brian
The problem with doing something right the first time is that nobody appreciates how difficult it was.
 
Many thanks bgaines72.

This seems to point me in the right direction.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top