Gary Devenay

Web Development

Random Image User Control

July25

Displaying random images through JavaScript is becoming a bit ‘old hat’. If your are regularly updating your images and find yourself updating your JavaScript file each time, I don’t need to tell you that it gets a bit boring.

With ASP.NET using a custom user control can simply eliminate this problem. We can create a control that will look into the images folder, select all of the images, find a random one and display it on an asp:image control.

The code for this is shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
Protected void Page_Load(object sender, EventArgs e)
{
    //Show the path to the folder which contains the files you wish to randomly select from
    string directory = "/common/images/random/";
 
    //Create a string array to contain the images
    string[] images = Directory.GetFiles(HttpContext.Current.Server.MapPath(directory));
 
    //Check to see if any images exist and if so display a random one
    if (images.Length > 0)
    {
        int rnd = new Random().Next(0, images.Length);
        imgRandom.ImageUrl = directory + Path.GetFileName{images[rnd]);
    }
}


To display the random images, I have inserted an asp:Image on the control as follows:

1
2
3
<%@ Page Language="C#" MasterPageFile="~/web.master" AutoEventWireup="true" CodeFile="random.aspx.cs" Inherits="random" Title="Untitled Page" %>
 
<asp:Image ID="imgImage" runat="server" />
posted under ASP.NET
One Comment to

“Random Image User Control”

  1. On March 26th, 2010 at 8:57 pm Sukhdev Kanzariya Says:

    Thanks for help

Email will not be published

Website example

Your Comment: