At times we may want to automatically change images in a given time interval so that our web page will looks good. We can do it by taking Timer control and UpdatePanel. In the below example 9 images are taken and image of a banner is changing with these images periodically.A timer control is taken and it’s tick event will be fired in every 2 seconds as we can give the value in Interval property . The tick event of timer control will work as a trigger for the Update panel and the Image i.e.imgBanner present in the ContentTemplate will be changed in every 2 seconds.
<asp:ScriptManager ID="ScriptManager1" runat="server">
<asp:Timer ID="Timer1" runat="server" OnTick="gettickvalue" Interval="2000">
<asp:UpdatePanel ID="BannerPanel" runat="server" UpdateMode="Conditional">
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
<asp:Image ID="imgBanner" ImageUrl="~/images/banner_1.gif" runat="server" />
In the code section add the following lines.
protected void gettickvalue(object sender, EventArgs e)
Random RandomNumber = new Random();
int n = RandomNumber.Next(1, 9);
imgBanner.ImageUrl = System.String.Concat("images/banner_", n.ToString(), ".gif");
An object of Random class is created. Random class generates the random numbers..Then Next() method is called to generate the numbers within a specified range; here it is from 1 to 9. As a set of images which are like banner_1.gif, banner_2.gif…………….upto banner_9.gif are taken here. After getting the random number ,the Concat method of string is called ,taking 3 arguments, giving us the the full string which will be taken as the ImageUrl for the image i.e.imgBanner.