Home Home Home
Click to learn how to rotate images dynamically with the ASP.NET Image Control
    Step by Step ASP.NET Design Solutions
The Ultimate Website Design Guide Using ASP.NET and Adobe Photoshop

ASP.NET Image Control with SQL Server

This website is using the ASP.NET Image Control in our ASP.NET Master Page to rotate the scenic picture in the upper right corner of the page each time the page is visited or reloaded.

This Lesson builds on Step 1. SQL Server table and stored procedure where we created a SQL table to store our image data and a stored procedure to query the table. This lesson has the following steps:

Step 2. ASP.NET Image Control

Using Visual Studio create a new page called "gallery.aspx". On this page place an ASP.NET Image Control and call it "RotateImg". Using the ImageUrl property you can hardcode the path to an existing image on your site so you know that the control is working before we hookup the database query to it. Your page should look like this example:

<%@ Page Language="C#" CodeFile="gallery.aspx.cs" Inherits="gallery" %>

<td><h1>ASP.NET Image Control Example</h1></td>
<td><p><asp:Image ID=RotateImg ImageUrl="/images/rotate/rotate1.jpg" runat=server /></p>
<p>Reload the page to change the image.</p>

Open the code behind that was automatically created called gallery.aspx.cs. Without getting to fancy we'll use the Page_Load subroutine to store our database query code.

As you can see in the example below we're calling the SQL Server stored procedure we created in Step 1 called sp_images_random. We know our stored procedure is hardcoded to return only 1 image and we assign that value to the ImageUrl property of the ASP.NET Image Control we created above.

Now when we load the page gallery.aspx a new image is displayed every time.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
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;

public partial class gallery : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
    string strConnection = ConfigurationSettings.AppSettings["DBConnect"];

    SqlConnection objConnection = new SqlConnection(strConnection);

    SqlCommand objCommand = new SqlCommand("sp_images_random", objConnection);
    objCommand.CommandType = CommandType.StoredProcedure;        

    SqlDataReader objReader = objCommand.ExecuteReader();
    while (objReader.Read() == true)
       RotateImg.ImageUrl= (string)objReader["url"];


Test Drive

You can test drive the gallery.aspx page we created above to see how it works.

Next Lesson

In Step 3. ASP.NET User Control we'll make our page design more modular and reusable by using a User Control to store the Image Control and database query.

Privacy Policy Copyright © 2010 dotnetdesignguide.com  Webmaster