How can I display an image randomly in ASP.Net?

Your easiest and quickest way to do this would be to name all your images a number. Then use the "Random()" command and generate a number between 0 and the amount of files you have.

Otherwise you can loop through each file within the folder and put it into an array. Then do the Random() and selected the array index for your random image.

Thanks. I forgot how to make use of Random function already. can I have a sample code for it? Thanks again...

Dim RandomClass As New Random()
Dim rndNumber As Integer

rndNumber = (RandomClass.Next(01, 99))

This will choose a random number between 1 and 99. Keep in mind, when doing images, you should stick to a proper format and if you have less than 100 images, and plan on keeping it that way, include one zero in place of the first digit:

01 - 99
001 - 999
0001 - 9999

Now you don't honestly HAVE to follow this, but it prevents errors dramatically. Plus, if you get an error, do you really want to go through and rename a thousand images? :)

Here is something that you should probably use to grab the image:
Keep in mind I use T_*.jpg for all my "thumbnails".

'Random Image
Public Function RndImage() As String
	Dim rnd As New Random()
	'The below is for image names that start with "T_" and are jpeg.
	Dim ID As String = "T_*.jpg"
	Dim IDArr() As String = ID.split("*")
	Dim images() As String = System.IO.Directory.GetFiles((Server.MapPath("\images\"), ID)
	Dim imageToDisplay As String
	if CountPhotos(ID) < 1 then imageToDisplay = "nopicture"
	Do While Len(imageToDisplay) < 1
		imageToDisplay = images(rnd.Next(images.Length))
	loop
	Return ("\images\" & IDArr(0) & imageToDisplay & IDArr(1))
End Function

Public Function CountPhotos(ByVal ID As Long) As Integer
	Dim numero As Integer = 0
	Dim strPath As String = (Server.MapPath("\images\") & ID)
	Dim strFiles As String = Dir(strPath)
	Do Until Len(strFiles) = 0
		numero += 1
		if numero > 0 then exit do
	Loop
	CountPhotos = numero
End Function

This code is untested, so let me know if you have problems.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.