C# .NET - how to display different images in gridview

Asked By karthi keyan on 21-Nov-08 01:41 AM
i want to display images in gridview using item template

Re :: Images in Gridview Template Field

Shailendrasinh Parmar replied to karthi keyan on 21-Nov-08 01:51 AM

See the following articles

http://www.codeproject.com/KB/aspnet/GridImage.aspx   (Good Article)

http://www.codeproject.com/KB/aspnet/Thumbnail_Images.aspx

http://www.devasp.net/net/articles/display/692.html

Hope this helps.

re

Web Star replied to karthi keyan on 21-Nov-08 01:59 AM

Populating the GridView Control:

The next step is to populate the GridView control with data as well as images. Take a look at the code below which is used to populate the GridView.

private void BindData()

{

SqlConnection myConnection = new SqlConnection(ConnectionString);

SqlDataAdapter ad = new SqlDataAdapter("SELECT UserID, FirstName, LastName,Url FROM Users", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds);

GridView1.DataSource = ds;

GridView1.DataBind();

}

As, you can see the above code is pretty straight forward and you might have done this thousand of times. Now, let's see how we can display the images into the GridView control.

Display Images into the GridView Control:

The first thing you need to do is to add a template column in the GridView control. Once, you have added the template column simply add an Image server control inside the template column. The HTML code of the GridView will look something like the following code:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4">

<Columns>

<asp:BoundField DataField="UserID" HeaderText="UserID" />

<asp:BoundField DataField="FirstName" HeaderText="First Name" />

<asp:TemplateField HeaderText="Image">

<ItemTemplate>

<asp:Image ID="Image1" ImageUrl='<%# (string) FormatImageUrl( (string) Eval("Url")) %>' runat="server" />

</ItemTemplate>

</asp:TemplateField>

</Columns>

<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />

<RowStyle BackColor="White" ForeColor="#330099" />

<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />

<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />

<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />

</asp:GridView>


I have made the Image tag bold in the above code so you will easily identify it. Next thing we need to see is the purpose of the FormatImageUrl method which is used to assign the correct url to the ImageUrl property of the Image control.

protected string FormatImageUrl(string url)

{

if (url != null && url.Length > 0)

return ("~/" + url);

else return null;

}

The purpose of "~/" is to map the url relative to the root. This means that the Image control will look for the ImageUrl starting from the root of the website.

Now, if you run your application provided that there are images in the directory which you are using you will see image column in the GridView control just like shown below:

 

Re :: Display Images in Gridview

Shailendrasinh Parmar replied to karthi keyan on 21-Nov-08 02:00 AM
GridView Examples for ASP.NET 2.0: Displaying Images in a GridView Column
 

Click http://msdn.microsoft.com/en-us/library/aa479339.aspx to return to the TOC.

In the ASP.NET 1.x class I teach, the course-long project for the students is to create an online photo album, one that allows visitors to upload images and provide metadata about the images, such as a description, a title, and so on. The data model my students typically use consists of a Pictures table with the following fields:

  • PictureID—a synthetic primary key, typically an integer field setup as an IDENTITY.
  • Title—a short title for the picture.
  • DateAdded—the date/time the picture was uploaded.
  • PictureUrl—the path to the uploaded image file.

When users want to add a new image to the photo album site, they must visit a particular page that contains a file upload control along with form input fields querying them for the other bits of information. When they submit the form, the picture on their computer is uploaded to the Web server's file system and a new row is added to the Pictures table. The PictureUrl field is set to the virtual path of the uploaded image file.

There's an additional page that lists all pictures in the photo album using a DataGrid. To display an image in a column in a DataGrid in ASP.NET 1.x you have to use a TemplateColumn with an Image Web control inside the TemplateColumn. With ASP.NET 2.0 the GridView includes an ImageField that can be used to display an image in a column of the GridView.

Imagine that we had the data model discussed previously and wanted to display all of the pictures in a GridView, displaying the PictureID, Title, and DateAdded fields each in a column and the actual image itself in an additional column.

To accomplish this we'd first grab the data using a data source control and then add a GridView bound to that data source control. This GridView would have four BoundField columns, meaning that instead of seeing the actual image we'd see the actual image path when viewing the GridView in a browser. To display the actual image, we need to edit the GridView's columns, removing the PictureUrl BoundField and replacing it with an ImageField. To edit a GridView's columns simply click on the Edit Columns link from the GridView's Smart Tag. This will bring up a dialog box like the one shown in Figure 25. Delete the PictureUrl BoundField and add in an ImageField. Finally, set the ImageField's DataImageUrlField to the name of the DataSource field that contains the image path—PictureUrl.

Figure 25

This will result in a GridView with the following declarative syntax:

<asp:GridView ID="GridView1" Runat="server" 
  DataSource='<%# GetData() %>' AutoGenerateColumns="False" 
  BorderWidth="1px" BackColor="White" CellPadding="3" BorderStyle="None" 
  BorderColor="#CCCCCC" Font-Names="Arial">
    <FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
    <PagerStyle ForeColor="#000066" HorizontalAlign="Left" 
      BackColor="White"></PagerStyle>
    <HeaderStyle ForeColor="White" Font-Bold="True" 
      BackColor="#006699"></HeaderStyle>
    <Columns>
        <asp:BoundField HeaderText="Picutre ID" DataField="PictureID">
            <ItemStyle HorizontalAlign="Center" 
              VerticalAlign="Middle"></ItemStyle>
        </asp:BoundField>
        <asp:BoundField HeaderText="Title" DataField="Title"></asp:BoundField>
        <asp:BoundField HeaderText="Date Added" DataField="DateAdded" 
          DataFormatString="{0:d}">
            <ItemStyle HorizontalAlign="Center"></ItemStyle>
        </asp:BoundField>
        <asp:ImageField DataImageUrlField="PictureURL"></asp:ImageField>
    </Columns>
    <SelectedRowStyle ForeColor="White" Font-Bold="True" 
       BackColor="#669999"></SelectedRowStyle>
    <RowStyle ForeColor="#000066"></RowStyle>
</asp:GridView>

Since the Northwind database does not have a table with an image path, we'll have to programmatically create our own data model to see this demo in action. The following code in our ASP.NET page creates a DataTable with the appropriate schema and populates the DataTable with four records.

Creating a DataTable Programmatically (Visual Basic)

Function GetData() As DataTable
    ' This method creates a DataTable with four rows.  Each row has the
    ' following schema:
    '   PictureID      int
    '   PictureURL     string
    '   Title          string
    '   DateAdded      datetime
    Dim dt As New DataTable()
    ' define the table's schema
    dt.Columns.Add(New DataColumn("PictureID", GetType(Integer)))
    dt.Columns.Add(New DataColumn("PictureURL", GetType(String)))
    dt.Columns.Add(New DataColumn("Title", GetType(String)))
    dt.Columns.Add(New DataColumn("DateAdded", GetType(DateTime)))
    ' Create the four records
    Dim dr As DataRow = dt.NewRow()
    dr("PictureID") = 1
    dr("PictureURL") = ResolveUrl("~/DisplayingImages/Images/Blue hills.jpg")
    dr("Title") = "Blue Hills"
    dr("DateAdded") = New DateTime(2005, 1, 15)
    dt.Rows.Add(dr)
    dr = dt.NewRow()
    dr("PictureID") = 2
    dr("PictureURL") = ResolveUrl("~/DisplayingImages/Images/Sunset.jpg")
    dr("Title") = "Sunset"
    dr("DateAdded") = New DateTime(2005, 1, 21)
    dt.Rows.Add(dr)
    dr = dt.NewRow()
    dr("PictureID") = 3
    dr("PictureURL") = _
      ResolveUrl("~/DisplayingImages/Images/Water lilies.jpg")
    dr("Title") = "Water Lilies"
    dr("DateAdded") = New DateTime(2005, 2, 1)
    dt.Rows.Add(dr)
    dr = dt.NewRow()
    dr("PictureID") = 4
    dr("PictureURL") = ResolveUrl("~/DisplayingImages/Images/Winter.jpg")
    dr("Title") = "Winter"
    dr("DateAdded") = New DateTime(2005, 2, 18)
    dt.Rows.Add(dr)
    Return dt
End Function

Creating a DataTable Programmatically (C#)

DataTable GetData()
{
    // This method creates a DataTable with four rows.  Each row has the
    // following schema:
    //   PictureID      int
    //   PictureURL     string
    //   Title          string
    //   DateAdded      datetime
    DataTable dt = new DataTable();
    // define the table's schema
    dt.Columns.Add(new DataColumn("PictureID", typeof(int)));
    dt.Columns.Add(new DataColumn("PictureURL", typeof(string)));
    dt.Columns.Add(new DataColumn("Title", typeof(string)));
    dt.Columns.Add(new DataColumn("DateAdded", typeof(DateTime)));
    // Create the four records
    DataRow dr = dt.NewRow();
    dr["PictureID"] = 1;
    dr["PictureURL"] = ResolveUrl("~/DisplayingImages/Images/Blue hills.jpg");
    dr["Title"] = "Blue Hills";
    dr["DateAdded"] = new DateTime(2005, 1, 15);
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr["PictureID"] = 2;
    dr["PictureURL"] = ResolveUrl("~/DisplayingImages/Images/Sunset.jpg");
    dr["Title"] = "Sunset";
    dr["DateAdded"] = new DateTime(2005, 1, 21);
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr["PictureID"] = 3;
    dr["PictureURL"] = 
      ResolveUrl("~/DisplayingImages/Images/Water lilies.jpg");
    dr["Title"] = "Water Lilies";
    dr["DateAdded"] = new DateTime(2005, 2, 1);
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr["PictureID"] = 4;
    dr["PictureURL"] = ResolveUrl("~/DisplayingImages/Images/Winter.jpg");
    dr["Title"] = "Winter";
    dr["DateAdded"] = new DateTime(2005, 2, 18);
    dt.Rows.Add(dr);
    return dt;
}

To bind this data to the GridView we can set the GridView's DataSource property to the GetData() method like so:

<asp:GridView Runat="server" DataSource='<%# GetData() %>' ...>
  ...
</asp:GridView>

Finally, we need to call Page.DataBind() in the Page_Load event handler to bind the GridView's DataSource.

Page_Load Event Handler (Visual Basic)

Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Page.DataBind()
End Sub
Page_Load Event Handler (C#)
void Page_Load(object sender, EventArgs e)
{
    Page.DataBind();
}

The end result is a GridView that shows the image referenced by the PictureUrl path (see Figure 26).

Figure 26

Don't be daunted by the length of this example's code—the length is due entirely to the fact that we had to synthetically create a data model with a table that has an image path field. Had the Northwind database had such a table, this example—like the previous ones—wouldn't have required a lick of code.

Hope this helps.

Re :: Display Images in Gridview
Shailendrasinh Parmar replied to karthi keyan on 21-Nov-08 02:02 AM

Storing Images to Database and Retrieving to GridView

Introduction

Over the internet, one can easily find a lot of references for uploading images to a database. The major problem arises when one has to retrieve these images and display them in some server control, like the GridView control. In this article we will tackle exactly that. So let's begin... shall we?

Prerequisites

This tutorial assumes that you own a copy of Visual Studio 2005 or Visual Web Developer Express. It also assumes that you are familiar with ASP.Net 2.0 basics and have worked with SQL Express before.

Creating the File Upload page:

We will start with the default page, from where we will provide the user the functionality to upload the images. Open Default.aspx and switch to design-view. Drag-n-drop controls from the toolbox onto the page to create a similar form:

The Text-Box followed by the Browse button is the HTML File Input control. After adding this control onto the form switch to Source-View and add modify the control's source to include runat="server". This will allow us to use the control as a server control.

In the above page, the controls are as follows:

  1. fileUpload - To select the file to upload.
  2. txtTitle - The title of the image.
  3. btnUpload - On click uploads the selected image.
  4. lnkView - The View Images link that loads the images from the databases inside a GridView.
  5. Validation Controls - The Required Field Validation Controls in order to make sure that Title and File are selected.

Let us suppose that the Database File already exists. If not then add one now by right-clicking the Project and clicking on Add Item. Select Database and name it imgDB.mdf. The database will contain one table which is as follows:

 

Switch to the code-behind class of Default.aspx and add a button click event handler for btnUpload.

Protected Sub btnUpload_Click(..., ...) Handles btnUpload.Click

        Dim intLength As Integer

        Dim arrContent As Byte()

 

        If fileUpload.PostedFile Is Nothing Then

            lblStatus.Text = "No file specified."

            Exit Sub

        Else

            Dim fileName As String = fileUpload.PostedFile.FileName

            Dim ext As String = fileName.Substring(fileName.LastIndexOf("."))

            ext = ext.ToLower

 

            Dim imgType = fileUpload.PostedFile.ContentType

            If ext = ".jpg" Then

            ElseIf ext = ".bmp" Then

            ElseIf ext = ".gif" Then

            ElseIf ext = "jpg" Then

            ElseIf ext = "bmp" Then

            ElseIf ext = "gif" Then

            Else

                lblStatus.Text = "Only gif, bmp, or jpg format files supported."

                Exit Sub

            End If

 

            intLength = Convert.ToInt32(fileUpload.PostedFile.InputStream.Length)

            ReDim arrContent(intLength)

 

            fileUpload.PostedFile.InputStream.Read(arrContent, 0, intLength)

 

            If Doc2SQLServer(txtTitle.Text.Trim, arrContent, intLength, imgType) = True Then

                lblStatus.Text = "Image uploaded successfully."

            Else

                lblStatus.Text = "An error occured while uploading Image... Please try again."

            End If

        End If

End Sub

What this function does is that it grabs the file selected in the File Input control and gets its extension. If the file is of type jpg, bmp, or gif, then it proceeds otherwise it throws an error. This terminates upload if the selected file is not an image of supported format.

After checking the file format, we get the length of the file and create a Byte Array of that same length. This Byte Array will store our file/image for us. Using the InputStream.Read method of fileUpload control, we load the image into the Byte Array.

After having saved the file into the byte array, we call our function Doc2SQLServer to store the file. We pass in the title that was supplied by the user, the byte array (which is our image), the total length, and the type of image.

In the Doc2SQLServer method, we create a connection to our SQL Express database and create an insertion command. After connecting to the database, we execute the query and store our image and its information to the database. Below is the Doc2SQLServer method.

Protected Function Doc2SQLServer(ByVal title As String, ByVal Content As Byte(), ByVal Length As Integer, ByVal strType As String) As Boolean

        Try

            Dim cnn As Data.SqlClient.SqlConnection

            Dim cmd As Data.SqlClient.SqlCommand

            Dim param As Data.SqlClient.SqlParameter

            Dim strSQL As String

 

            strSQL = "Insert Into tblImage(imgData,imgTitle,imgType,imgLength) Values(@content,@title,@type,@length)"

 

            Dim connString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=""|DataDirectory|\imgDB.mdf"";Integrated Security=True;User Instance=True"

            cnn = New Data.SqlClient.SqlConnection(connString)

 

            cmd = New Data.SqlClient.SqlCommand(strSQL, cnn)

 

            param = New Data.SqlClient.SqlParameter("@content", Data.SqlDbType.Image)

 

            param.Value = Content

            cmd.Parameters.Add(param)

 

            param = New Data.SqlClient.SqlParameter("@title", Data.SqlDbType.VarChar)

            param.Value = title

            cmd.Parameters.Add(param)

 

            param = New Data.SqlClient.SqlParameter("@type", Data.SqlDbType.VarChar)

            param.Value = strType

            cmd.Parameters.Add(param)

 

            param = New Data.SqlClient.SqlParameter("@length", Data.SqlDbType.BigInt)

            param.Value = Length

            cmd.Parameters.Add(param)

 

            cnn.Open()

            cmd.ExecuteNonQuery()

            cnn.Close()

            Return True

        Catch ex As Exception

            Return False

        End Try

End Function

The Image Grabber

Next we create a web-page that will grab the image whose id is passed to it as a query string. Right-click the project in solution explorer and add a web-page imgGrab.aspx.

Define the page_load method as follows:

Protected Sub Page_Load(...,...) Handles Me.Load

        Try

            Dim ds As New DataSet

            Dim da As SqlClient.SqlDataAdapter

            Dim arrContent As Byte()

            Dim dr As DataRow

            Dim strSql As String

 

            strSql = "Select * from tblImage Where imgId=" & Request.QueryString("ID")

 

            Dim connString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=""|DataDirectory|\imgDB.mdf"";Integrated Security=True;User Instance=True"

            da = New SqlClient.SqlDataAdapter(strSql, connString)

            da.Fill(ds)

            dr = ds.Tables(0).Rows(0)

            arrContent = CType(dr.Item("imgData"), Byte())

            Dim conType As String = dr.Item("imgType").ToString()

            Response.ContentType = conType

            Response.OutputStream.Write(arrContent, 0, dr.Item("imgLength"))

            Response.End()

        Catch ex As Exception

 

        End Try

End Sub

What this does is quite simple. It gets the image data whose id is passed in and writes it to the web-page. Response.ContentType sets the web-page as an image content holder and when we write the complete byte array to the response stream, we actually get the image.

Loading Images into the GridView Control

A major problem faced by developers is when loading images back into the datagrid or the new gridview control. I myself faced long hours trying to come up with a solution for this, which in the end was a simple procedure.

Create a new-page, Viewer.aspx and add a GridView onto it. (This page is linked from the Default.aspx page via lnkView). Name the GridView imgGrid and click on the small box located at the upper-right corner of the control.

Click on Edit Columns to open the Fields Dialog as shown below.

In this dialog, uncheck "Auto-generate fields" and add two fields; a bound field and an image field. For the bound field set the column header text to Title and the DataField property to imgTitle (This will bind this column to the imgTitle column in the dataset to which we will load our table data). As for the image field, set the caption to Picture and the DataImageUrlField to imgFile. You might think where this imgFile comes from, especially since the database does not contain a column with such a name.

Switch to the code-behind class and create the page_load event as follows:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim ds As New DataSet

        Dim da As SqlClient.SqlDataAdapter

        Dim strSQL As String

 

        strSQL = "Select imgId,imgTitle from tblImage"

        Dim connString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=""|DataDirectory|\imgDB.mdf"";Integrated Security=True;User Instance=True"

        da = New SqlClient.SqlDataAdapter(strSQL, connString)

        da.Fill(ds)

 

        ds.Tables(0).Columns.Add("imgFile")

 

        For Each tempRow As DataRow In ds.Tables(0).Rows

            tempRow.Item("imgFile") = ("imgGrab.aspx?id=" & tempRow.Item("imgID"))

        Next

 

        imgGrid.DataSource = ds

        imgGrid.DataBind()

End Sub

What this function does is the simple task of grabbing data from the database. It grabs two columns, imgId and imgTitle. What it does afterwards is the key concept... and the few-lines of code that marks the solution to a big problem.

After filling in the dataset, we know that it contains one table, at index 0 of course. We add a custom column "imgFile" to it.

After that, we traverse through each dataRow in the table. And for each row, we make a call to our imgGrab.aspx page with the id from that row. We set this equal to the record for imgFile for that row.

Thus on display of the GridView, for each row being displayed, the imgGrab.aspx web-page is called and the image is displayed in return.

A screen-shot of the resulting grid:


Hope this helps.

TRY THIS
C_A P replied to karthi keyan on 21-Nov-08 05:21 AM

Explanation:

This Article is continuity of our Article http://www.dotnet-friends.com/Articles/ASP/ARTinASP45cf7ec8-f523-4b10-ac52-06676d7034d1.aspx. Here We will discuss about displaying a unique image for each user. This means every user will view an image he is allowed to or he have uploaded in his own profile


  • For showing a static image in a gridview read http://msdn2.microsoft.com/en-us/library/aa479350.aspx.
  • For saving and displaying Users/Members Profile Images, Read the complete and detailed version at
    http://dotnet-friends.com/articles/asp/artinasp03e650de-2b15-4fb1-9bdb-aad1a1e5ac5c.aspx.

Article Requierments:

To make sure we undertsand the Article better, before we move next we need to make sure that we know about the following:

  • GridView/DataGrid Control
  • ASP .NET 2.0 ObjectDataSource
  • ASP .NET 2.0 Membership Objects
  • ASP .NET Generic Handlers

Now, when we made sure that we have the basic knowledge of what we will use in our article, we can go a head. Our Gridview look like this;

<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1" AutoGenerateColumns=false  >
<Columns>
<asp:BoundField DataField="id" HeaderText="id" SortExpression="id" />
<asp:BoundField DataField="message" HeaderText="message" SortExpression="message" />
<asp:TemplateField HeaderText="User Name">
<asp:TemplateField HeaderText="Picture">
<ItemTemplate>
<img src='PicHandler.ashx?UserName=<%# Eval("username")%>' />
</ItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>

Instead of using BoundField we are using ItemTemplate to cerate our own customised Template. We are accessing our Images through a link which is pointing to our Handler (.ashx). So how does actually the Handler access images and present them to us? Handler process our Request and cerate a Proper Responce to it. This Responce Handling is actually what a Handler all about.


Here we will use an ObjectDataSource Object to access the current logged in user. Our ObjectDatasource Look like this:

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="GetUsersData"
SelectMethod="GetUserName"
OldValuesParameterFormatString="original_{0}"/>

Here GetUsersData is our Class and GetUserName is a Static Method which brings the Current Logged-in User. To detrermin the Current Logged-in User you can use Membership and MembershipUser Objects.


We can create a Handler by right clicking on the Project > Add New Item > Select Generic Handler > Add . You can edit this newly created Handler. Now see how does our Handler look like;

<%@ WebHandler Language="C#" Class="PicHandler" %>

using System;
using System.Web;
using System.IO;
using System.Configuration;

public class PicHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
context.Response.Cache.SetCacheability(HttpCacheability.Server);
context.Response.BufferOutput = false;
// Setup the PhotoID Parameter
Stream stream = null;
string userName = context.Request.QueryString["UserName"];
if (userName != null && userName != "")
{
stream = OurUsersData.GetUserPic(userName);
if (stream == null)
{
stream = OurUsersData.GetUserPic("defaultPicture");
}

}
// Write image stream to the response stream
const int buffersize = 1024 * 16;
byte[] buffer = new byte[buffersize];
int count = stream.Read(buffer, 0, buffersize);
while (count > 0)
{
context.Response.OutputStream.Write(buffer, 0, count);
count = stream.Read(buffer, 0, buffersize);
}
}

public bool IsReusable
{
get{ return false;}
}
}

Where "ourUsersData" is Class defined in the "App-code" folder and "GetUserPic" is a satic function. The bold block is showing how to get an Image. If the user did not uploaded his picture the default image will be displayed instead.


How are we accessing our Database? If you are saving images to the User Profile in ASP .NET 2.0 then you need to create a method for accessing an image from the Profile System otherwise, if you are saving Images in your own Database then you can access the database by using ADO .NET 2.0. Make sure that the return type of your Method is a Stream.

TRY THIS LINK
C_A P replied to karthi keyan on 21-Nov-08 05:25 AM
http://msdn.microsoft.com/en-us/library/bb288032.aspx
http://www.codeproject.com/KB/aspnet/GridImage.aspx
http://www.dotnetspider.com/forum/166594-How-display-image-gridview.aspx
http://www.codedigest.com/Articles/ASPNET/6_GridView_with_Image.aspx
Display images from folder in GridView
C Mcdonald replied to C_A P on 12-Jan-09 11:46 AM

Hi,
I have a folder with all our Staff images that are saved by their staff number. I have created a little C# webpart to display the details of all new employees with Gridview in Visual Studio 2008. I can bring in all their information but can't get their image to display. Do I have to copy all images into a database and then display or should I be able to call the images from the folder?

Thanks,

Caitriona

dfg
abdhesh mishra replied to karthi keyan on 20-Mar-09 06:39 AM

jai ho

sonalika replied to Shailendrasinh Parmar on 26-Aug-10 02:25 PM
.aspx code




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="viewimage.aspx.cs" Inherits="viewimage" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <table align="center">
                <tr>
                    <td>
                         
                        <asp:GridView ID="GridView1" runat="server" 
        AllowPaging="True" PageSize="2" AutoGenerateColumns="False" >
                            <Columns>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("imageName") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Image">
                                    <ItemTemplate>
                                             <asp:Image id="Image1" runat="server" ImageUrl='<%# String.Format("Handler1.ashx?image={1}", Eval("image")) %>' Height="76px" Width="106px"></asp:Image>
                                             <%--<asp:LinkButton ID="lnkpdf" runat="server" OnClick="lnktest_Click1" Text='<%# Eval("Pdf") %>' CommandArgument='<%# Eval("Pdf") %>'> </asp:LinkButton>--%>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                        </asp:GridView>
                        
    </td>
                </tr>
            </table>
            
                
                <%--<asp:LinkButton ID="lnktest" runat="server" OnClick="lnktest_Click"> open file</asp:LinkButton>--%>
    
    
    </div>
    </form>
</body>
</html>
-------------------------------------------------------------------------------------------------------------------------------------------

.aspx.cs code

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.Sql;

public partial class viewimage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=SONAL-PC\\SQLEXPRESS;Initial Catalog=Flotech;Integrated Security=True ");
        //con.ConnectionString = ConfigurationManager.ConnectionStrings["medico"].ConnectionString;
        con.Open();

        string query = "SELECT * FROM image";
        SqlCommand cmd = new SqlCommand(query, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        //GridView1.AutoGenerateDeleteButton.Equals("true");
        //GridView1.AutoGenerateEditButton.Equals("true");
        //Response.ContentType = "image/jpg";

        //Response.AppendHeader("Content-Disposition", "attachment; filename=imgfile");

        //Response.TransmitFile(Server.MapPath(test1));
        

        Response.End();

        con.Close();

    }
   
    protected void lnktest_Click1(object sender, EventArgs e)
    {
        LinkButton lb = sender as LinkButton;

        string test1 = lb.CommandArgument;
        //Response.ContentType = "image/jpg";

        //Response.AppendHeader("Content-Disposition", "attachment; filename=imgfile");

        //Response.TransmitFile(Server.MapPath(test1));

        //Response.End();
    }
}