I have tutorial about random image with PHP on previous post, and now I’ll share about random image with ASP.NET. Basically, It has same method to make random image with PHP, and only different in scripting.

There are some step to make random image with ASP.NET:

1. Create new website, with C# language.
Preview1

2. Right click root site on solution explorer->Choose new Item->and Web Form. Give name RandomImage.aspx and check in “Place code in separate file”.
preview2

3. Create new folder for images. Example: I create Images folder on root site.

Preview3
Copy paste all image on it, and rename to 1.jpg, 2.jpg, 3.jpg, … n.jpg
Preview4

4. Add image control on RandomImage.aspx, like this preview bellow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RandomImage.aspx.cs" Inherits="RandomImage" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Image Random</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Image ID="ImageRandom" runat="server" width="300px"/>
    </div>
    </form>
</body>
</html>

5. Add this script on RandomImage.aspx.cs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
 
public partial class RandomImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Random objRnd = new Random();
        int intRnd = objRnd.Next(6) + 1; //set it to your images count, i use 6 images.
        ImageRandom.ImageUrl = "~/Images/" + intRnd.ToString() + ".jpg";
        ImageRandom.AlternateText = "Picture" + intRnd.ToString();
    }
}

6. Try to view in browser and refresh it to get it change.

Preview5

Finish. Coding with ASP.NET is fun^^

Sphere: Related Content

Tags: , ,
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...






Related Post:


Leave a Comment

Blogroll Link Update