Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 759
  • Last Modified:

Random pictures in ASP (C#)

Hello experts,
I have a random picture view generator that making me a problem.

When i'm adding <asp:Image runat="server" ID="img1" /> it showing me exactly same picture as previous.
Question: How to show different picture by each ID in same page...

Code attached.

Many 10x
aspx.cs
 
protected void Page_Load(object sender, EventArgs e)
    {
        SetNextImage();
    }
    private void SetNextImage()
    {
        string path = Server.MapPath("~/Images/Promo/");
        string[] files = Directory.GetFiles(path);
        Random r = new Random();
        FileInfo fi = new FileInfo(files[r.Next(0, files.Length)]);
        img.ImageUrl = "~/Images/Promo/" + fi.Name;
        img1.ImageUrl = "~/Images/Promo/" + fi.Name;
    }
 
 
aspx
 
  <asp:ScriptManager ID="ScriptManager1" runat="server" >
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Timer ID="Timer1" runat="server" 
                     Interval="5000">
                </asp:Timer>
                <asp:Image runat="server" ID="img" />
                <asp:Image runat="server" ID="img1" />
            </ContentTemplate>
        </asp:UpdatePanel>

Open in new window

0
DanSmir
Asked:
DanSmir
  • 2
1 Solution
 
GuitarRichCommented:
I think you have missed the timer.tick event out so its not updating based on the timer.
try this code:
 

		<asp:Timer ID="Timer1" runat="server" interval="5000" ontick="Timer1_Tick">
		</asp:Timer>
 
// code behind:
	protected void Timer1_Tick(object sender, EventArgs e)
	{
		SetNextImage();
	}

Open in new window

0
 
DanSmirAuthor Commented:
GuitarRich:

10x,
But my problem is not a timer...

I need to show different FileInfo fi = new FileInfo(files[r.Next(0, files.Length)]); by ID...
0
 
demi-osCommented:
if i understood you correctly the bellow code is what you are asking for
    private void SetNextImage()
    {
        string path = Server.MapPath("~/Images/Promo/");
        string[] files = Directory.GetFiles(path);
        Random r = new Random();
        FileInfo fi1 = new FileInfo(files[r.Next(0, files.Length)]);
        FileInfo fi2 = new FileInfo(files[r.Next(0, files.Length)]);
        img.ImageUrl = "~/Images/Promo/" + fi1.Name;
        img1.ImageUrl = "~/Images/Promo/" + fi2.Name;
    }

Open in new window

0
 
DanSmirAuthor Commented:
demi-os

any many 10x. It works!!!!!!
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now