O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.7. Displaying an Image from a Database in a Web Forms Control

Problem

You need to display an image from a database column in an ASP.NET control.

Solution

Fill an ASP.NET Image control from a database field by pointing the ImageUrl property of an Image control to a web page that retrieves the image from the database. The solution contains three files: the Web Forms page to display the image, its code-behind file, and the code-behind page that serves the image.

The Web Forms page sample code displays the employee image in the Image control employeeImage. The code for the Web Forms page is shown in Example 7-13.

Example 7-13. File: ADOCookbookCS0707.aspx

<asp:Image id="employeeImage"
    style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 56px"
    runat="server">
</asp:Image>

The code-behind used with the Web Forms page contains one event handler:

Form.Load

Sets the ImageUrl property of the employeeImage Image control to the web page that serves the employee image, then a parameter passed in the URL indicates the employee ID to retrieve.

The C# code for the code-behind is shown in Example 7-14.

Example 7-14. File: ADOCookbookCS0707.aspx.cs

using System; 

//  . . . 

private void Page_Load(object sender, System.EventArgs e)
{
    // Set the image URL to the page containing just the image.
    employeeImage.ImageUrl = "ADOCookbookCS0707b.aspx?EmployeeId=" +
        employeeIdTextBox.Text;
}

The code-behind that serves the image contains one event handler:

Form.Load

Retrieves the image from the database for the specified ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required