Click here to Skip to main content
15,890,670 members
Articles / Web Development / ASP.NET
Tip/Trick

Add and Replace Picture From Web Application With Preview Functionality

Rate me:
Please Sign up or sign in to vote.
4.25/5 (3 votes)
18 Dec 2013CPOL 8.1K   74   5   2
Add and replace picture with preview functionality using the GridView control.

Introduction

The GridView control has a variety of functionalities. In this article I will use it as a preview container.

Suppose you have an image folder in your web application and that image folder has pictures for a slideshow or picture gallery or slider, etcetera. You might need to add a new picture there or replace an existing picture. For that I have used a GridView control so that you can preview all the pictures in the images folder and replace them if required.

Web1.jpg

Of course you can also add a new image; for that there is a file upload control ID. First of all, add an image folder to your web application as follows:

Web2.jpg

Controls on design

Now add a file-upload control and a button to add a new image. Add a GridView control, and your source code should look as follows in the source view:

XML
<asp:FileUpload runat="server" ID="FupMain" />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="Add" />
        <br />
        <br />
        <br />
<asp:GridView DataKeyNames="Name" AutoGenerateColumns="false" ID="GridView1"
            DataSource='<%#dt %>'  runat="server" onrowcommand="GridView1_RowCommand">
   <Columns>
        <asp:TemplateField HeaderText="Image">
        <ItemTemplate>
        <asp:Image ImageUrl='<%"~/images/"+ Eval("Name") %>' 
               runat="server" ID="img2" Height="100"Width="100" />
        </ItemTemplate>
        </asp:TemplateField>
       
        <asp:TemplateField HeaderText="Replace">
        <ItemTemplate>
        <asp:FileUpload runat="server" ID="fup" />
           <asp:LinkButton CommandName="replace" runat="server"Text="Ok" ID="btnRep" />
        </ItemTemplate>
        </asp:TemplateField>
   </Columns>
</asp:GridView>

Note the following:

  • GridView has a property, onrowcommand="GridView1_RowCommand".
  • GridView has two item-templates: one for the image control and another for the file-upload and link buttons.

Using Server Side Code

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
    public string[] arr;
    public DataTable dt;
    public DataRow dr;
    protected void Page_Load(object sender, EventArgs e)
    {
        // To get all the file names only of images directory
        arr = Directory.GetFiles(Server.MapPath("~\\") + 
          "images").Select(path => Path.GetFileName(path)).ToArray();
        //Gridview using dt as datasource
        //adding all the names of files to a datatable

        dt = new DataTable();
        dt.Columns.Add("name");
        for (int i = 0; i < arr.Length; i++)
        {
            dr = dt.NewRow();
            dr["name"] = arr[i].ToString();
            dt.Rows.Add(dr);
        }
        GridView1.DataBind();
    }
    // When you click OK after choosing a image to replace
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "replace")
        {
           //To get the specific row of gridview and then image name too
           LinkButton btn = (LinkButton)e.CommandSource;
           GridViewRow grow = (GridViewRow)btn.NamingContainer;
           FileUpload fup1 = (FileUpload)grow.FindControl("fup");
           string fileName = GridView1.DataKeys[grow.RowIndex].Value.ToString();
           //Reaplacing image
           if (fup1.HasFile)
            {
                string path = Server.MapPath("~/images/") + fileName;
                fup1.SaveAs(path);
            }
        }
    }
    // To add new image
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FupMain.HasFile)
        {
            string path = Server.MapPath("~/images/")+FupMain.FileName;
            FupMain.SaveAs(path);
        }
    }
}

History

  • 20 Dec. 2013: Initial version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
He started programming in year 2005 and since he achieves MCTS, MCA and MCPD in .Net Platform.
He works as Team Leader in one MNC Company. He is also consultant software developer for both windows and web.
He always contribute technical belief on several technical websites.

Comments and Discussions

 
BugNice sample but found a little bug... Pin
Carsten V2.018-Dec-13 9:20
Carsten V2.018-Dec-13 9:20 
Hello Brijesh,

I like your posting but I encountered a little bug, sorry. Rose | [Rose]

If Windows uses the "thumbs.db", this file in the folder of the images will be handled as image, too.
And this causes an error. The Gridview shows an empty row without image but only the button.

And clicking this button will result in an exception because on the one hand this is no image and on the
other hand the file is in use by Windows... Smile | :)

Suggestion: either you need a filter to read only images or remove manually this file from DataRow.

Thanks!
Carsten
GeneralRe: Nice sample but found a little bug... Pin
Brijesh Kr19-Dec-13 21:11
Brijesh Kr19-Dec-13 21:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.