Server Intellect
 
Home   Asp.Net Tutorials   What's New   Newsletter   More Resources
 
 
  Categories
Advanced Technologies
AJAX
Internet Browsers
Controls
Database
Email
Error Handling
File
Graphics
Website Navigation
Network
Performance
User Interface and Themes
Validation
Visual Web Developer
Web Services
XML
Suggest Tutorial


Navigator: Home - Tutorials - Graphics - Displaying a Random Image Each New Session ASP.NET & VB
Displaying a Random Image Each New Session ASP.NET & VB


ASP.NET Graphics Tutorial

This tutorial shows how to display a random image upon page load, and then keep that image until the session expires. A new random image will be chosen on new sessions, and remain. VB version.

Download the Full Working Version of this Project written with Visual Studio.NET VB 2005 Here!

Looking for the V#.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

This tutorial will show how we can choose a random image to display on page load, and this same image will remain for the duration of the session. This means that no matter how many times the visitor refreshes the page, the image will remain the same. However, if the browser is closed and the session ends, a new image will be chosen at random upon a new session start, and remain until the session ends, again.
First, we need to use System.IO:

Imports System.IO

For this example, we will simply use an IMG tag:

<form id="form1" runat="server">
<% Response.Write("<img src='" + chooseImage() + "' />")%>
</form>

On page load, we will call the method to choose the background image at random, but only if an image has not yet been selected this session.
The code-behind will look something like this:

Imports System.IO

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
chooseImage()
End Sub

Public Function chooseImage() As String
If Session("img") Is Nothing Then
Dim imgPath As String
Dim fileCount As Integer = Directory.GetFiles(Server.MapPath("/media/img/"), "*.*", SearchOption.TopDirectoryOnly).Length
fileCount = fileCount + 1
imgPath = "media/img/" & RandomNumber(1, fileCount) & ".jpg"
Session("img") = imgPath
Return imgPath
Else
Return Session("img").ToString()
End If
End Function

Private Function RandomNumber(ByVal min As Integer, ByVal max As Integer) As Integer
Dim random As New Random()
Return random.Next(min, max)
End Function
End Class

Download the Full Working Version of this Project written with Visual Studio.NET VB 2005 Here!

Looking for the V#.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!





 
  Developer Resources







Server Intellect Rocks