Upload Images To Server And Display Images As Thumbnail Inside Gridview And Show Popup On Mouseover Using jQuery.

Here I’ll explain how to upload images to server using fileuploader control and show them inside gridview as thumbnail image. A popup will appear on mouseover of the original image.

.aspx page

<%@ Page Title=”Display Images As Thumbnail Inside Grid And Popout On Mouseover using jQuery”
    Language=”C#” MasterPageFile=”~/Site.master” AutoEventWireup=”true” CodeFile=”Image_in_Gridview_using_Ajax.aspx.cs”
    Inherits=”Image_in_Gridview_using_Ajax” %>

<asp:Content ID=”Content1″ ContentPlaceHolderID=”HeadContent” runat=”Server”>
    <title>Display Images As Thumbnail Inside Grid And Popout On Mouseover using jQuery
    </title>
    <%–CSS and scripts for jQuery Calander starts–%>
    <link rel=”stylesheet” href=”http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css&#8221; />
    <script type=”text/javascript” src=”http://code.jquery.com/jquery-1.9.1.js”></script&gt;
    <script type=”text/javascript” src=”http://code.jquery.com/ui/1.10.3/jquery-ui.js”></script&gt;
    <link rel=”stylesheet” href=”/resources/demos/style.css” />
    <%–CSS and scripts for jQuery Calander ends–%>
    <style type=”text/css”>
        .popup
        {
            display: none;
            z-index: 100;
            position: absolute;
            max-height: 500px;
            max-width: 700px;
            margin-left: 110px;
            margin-top: -200px;
        }
        .close
        {
            position: absolute;
            margin-left: 675px;
            margin-top: -21px;
        }
    </style>
    <script type=”text/javascript”>
        $(function () {
            $(“#MainContent_txtDOB”).datepicker();
        });

        function validateNumber(text) {
            var age = text.value;
            if (isNaN(age)) {
                alert(‘Invalid input’);
                text.value = ”;
            }
        }

        function MaxLimit(txt) {
            if ($(txt).val().length > 200) {
                $(txt).val(”);
                alert(‘Invalid input, Max length is 200 characters.’);
            }
        }

        function ShowPopup(img) {
            var imgName = $(img).attr(‘alt’);
            $(‘[id$=divPopup]’).css(‘display’, ‘block’);
            $(‘[id$=imgClose]’).css(‘display’, ‘block’);
            $(‘[id$=imageShow]’).attr(‘src’, ‘Images/UserImage/’ + imgName);
        }

        $(document).ready(function () {
            $(‘[id$=imgClose]’).click(function () {
                $(‘[id$=divPopup]’).css(‘display’, ‘none’);
            });
        });
    </script>
</asp:Content>
<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”Server”>
    <h1>
        Display Images As Thumbnail Inside Grid And Popout On Mouseover using jQuery</h1>
    <br />
    <table width=”100%”>
        <tr>
            <td style=”width: 40%”>
                Name
            </td>
            <td>
                <input type=”text” id=”txtName” maxlength=”100″ runat=”server” />
            </td>
        </tr>
        <tr>
            <td>
                Age
            </td>
            <td>
                <input type=”text” id=”txtAge” runat=”server” maxlength=”3″ onchange=”validateNumber(this);” />
            </td>
        </tr>
        <tr>
            <td>
                Date Of Birth
            </td>
            <td>
                <input type=”text” id=”txtDOB” runat=”server” maxlength=”3″ />
            </td>
        </tr>
        <tr>
            <td>
                Contact No.
            </td>
            <td>
                <input type=”text” id=”txtContact” runat=”server” maxlength=”10″ onchange=”validateNumber(this);” />
            </td>
        </tr>
        <tr>
            <td>
                Address
            </td>
            <td>
                <textarea id=”txtAddress” runat=”server” rows=”7″ cols=”20″ onchange=”MaxLimit(this)”
                    onpaste=”MaxLimit(this)” onkeydown=”MaxLimit(this)”></textarea>
            </td>
        </tr>
        <tr>
            <td>
                Image
            </td>
            <td>
                <asp:FileUpload ID=”FileUpload1″ runat=”server” />
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
            <td>
                <asp:Button ID=”btnSave” Text=”Save” runat=”server” OnClick=”btnSave_Click” />
            </td>
        </tr>
    </table>
    <asp:HiddenField ID=”hdnId” Value=”0″ runat=”server” />
    <hr />
    <div id=”divPopup”>
        <img id=”imgClose” src=”Images/Close.png” alt=”Close” /><img id=”imageShow”
            width=”100%” /></div>
    <asp:GridView ID=”grdImage” runat=”server” AutoGenerateColumns=”false” DataKeyNames=”Id”
        EmptyDataText=”No record found!!!” Width=”100%” OnRowCommand=”grdImage_RowCommand”
        Style=”z-index: 10;”>
        <Columns>
            <asp:TemplateField HeaderText=”Sr.No.”>
                <ItemTemplate>
                    <%# Container.DataItemIndex+1 %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText=”Image” ItemStyle-Height=”100″ ItemStyle-Width=”100″>
                <ItemTemplate>
                    <img id=”imgUser” alt='<%# Eval(“NewImage”) %>’ src='<%# “Images/UserImage/t-“+Eval(“NewImage”).ToString() %>’
                        height=”100″ width=”100″ title='<%# Eval(“OrgImage”) %>’ onmousemove=”ShowPopup(this);” />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField=”Name” HeaderText=”Name” />
            <asp:BoundField DataField=”Age” HeaderText=”Age” />
            <asp:BoundField DataField=”DOB” HeaderText=”DOB” />
            <asp:BoundField DataField=”Contact” HeaderText=”Contact” />
            <asp:BoundField DataField=”Address” HeaderText=”Address” />
            <asp:TemplateField HeaderText=”Actions”>
                <ItemTemplate>
                    <asp:ImageButton ID=”imgEdit” CommandName=”editme” AlternateText=”Edit” runat=”server”
                        ImageUrl=”~/Images/edit.png” />
                    <asp:ImageButton ID=”imgDelete” CommandName=”deleteme” AlternateText=”Delete” runat=”server”
                        ImageUrl=”~/Images/delete.png” />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</asp:Content>

Code behind page

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Image_in_Gridview_using_Ajax : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadGrid();
        }
    }

    private void LoadGrid()
    {
        using (DBMLDataContext db = new DBMLDataContext())
        {
            grdImage.DataSource = db.Students.Where(x => x.Status == 1).Select(x => new { x.Id, x.Address, x.Age, x.Contact, x.DOB, x.Name, x.NewImage, x.OrgImage }).ToList();
            grdImage.DataBind();
        }
    }

    protected void btnSave_Click(object o, EventArgs e)
    {
        int Id = Convert.ToInt32(hdnId.Value);
        using (DBMLDataContext db = new DBMLDataContext())
        {
            if (Id == 0)
            {
                Student sd = new Student();
                sd.Address = txtAddress.Value;
                sd.Age = Convert.ToInt32(txtAge.Value);
                sd.Contact = txtContact.Value;
                sd.DOB = Convert.ToDateTime(txtDOB.Value);
                sd.Name = txtName.Value;
                sd.Status = 1;
                if (FileUpload1.HasFile)
                {
                    string fileName = string.Empty;
                    sd.OrgImage = FileUpload1.PostedFile.FileName;
                    fileName = DateTime.Now.Ticks.ToString() + FileUpload1.PostedFile.FileName;
                    sd.NewImage = fileName;
                    FileUpload1.SaveAs(Server.MapPath(“~/Images/UserImage/” + fileName));
                    GenerateThumbnails(100,100, FileUpload1.PostedFile.InputStream, Server.MapPath(“~/Images/UserImage/t-” + fileName));
                }
                else
                {
                    sd.OrgImage = “default_user.jpg”;
                    sd.NewImage = “default_user.jpg”;
                }
                db.Students.InsertOnSubmit(sd);
            }
            else
            {
                Student sd = db.Students.Where(x => x.Id == Id).SingleOrDefault();
                if (sd != null)
                {
                    string oldImage = sd.NewImage;
                    sd.Address = txtAddress.Value;
                    sd.Age = Convert.ToInt32(txtAge.Value);
                    sd.Contact = txtContact.Value;
                    sd.DOB = Convert.ToDateTime(txtDOB.Value);
                    sd.Name = txtName.Value;
                    if (FileUpload1.HasFile)
                    {
                        string fileName = string.Empty;
                        sd.OrgImage = FileUpload1.PostedFile.FileName;
                        fileName = DateTime.Now.Ticks.ToString() + FileUpload1.PostedFile.FileName;
                        sd.NewImage = fileName;
                        FileUpload1.SaveAs(Server.MapPath(“~/Images/UserImage/” + fileName));
                        if (!oldImage.Contains(“default_user”) && File.Exists(Server.MapPath(“~/Images/UserImage/” + oldImage)))
                        {
                            File.Delete(Server.MapPath(“~/Images/UserImage/” + oldImage));
                        }
                        GenerateThumbnails(100, 100, FileUpload1.PostedFile.InputStream, Server.MapPath(“~/Images/UserImage/t-” + fileName));
                    }
                }
            }
            db.SubmitChanges();
            Clear();
            LoadGrid();
        }
    }

    private void GenerateThumbnails(int width, int height, Stream sourcePath, string targetPath)
    {
        using (var image = System.Drawing.Image.FromStream(sourcePath))
        {
            var newWidth = width;
            var newHeight = height;
            var thumbnailImg = new Bitmap(newWidth, newHeight);
            var thumbGraph = Graphics.FromImage(thumbnailImg);
            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
            thumbGraph.DrawImage(image, imageRectangle);
            thumbnailImg.Save(targetPath, image.RawFormat);
        }
    }

    private void Clear()
    {
        hdnId.Value = “0”;
        txtAddress.InnerText = string.Empty;
        txtAge.Value = string.Empty;
        txtContact.Value = string.Empty;
        txtName.Value = string.Empty;
        txtDOB.Value = string.Empty;
    }
    protected void grdImage_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        using (DBMLDataContext db = new DBMLDataContext())
        {
            if (e.CommandName == “editme”)
            {
                int Id = (int)grdImage.DataKeys[((GridViewRow)(((ImageButton)e.CommandSource).NamingContainer)).RowIndex].Value;
                Student sd = db.Students.Where(x => x.Id == Id).SingleOrDefault();
                if (sd != null)
                {
                    txtAddress.InnerText = sd.Address;
                    txtAge.Value = sd.Age.ToString();
                    txtContact.Value = sd.Contact;
                    txtDOB.Value = sd.DOB.ToString();
                    txtName.Value = sd.Name;
                    hdnId.Value = sd.Id.ToString();
                }
            }
            else if (e.CommandName == “deleteme”)
            {
                int Id = (int)grdImage.DataKeys[((GridViewRow)(((ImageButton)e.CommandSource).NamingContainer)).RowIndex].Value;
                Student sd = db.Students.Where(x => x.Id == Id).SingleOrDefault();
                if (sd != null)
                {
                    db.Students.DeleteOnSubmit(sd);
                    db.SubmitChanges();
                    LoadGrid();
                }
            }
        }
    }
}

1

 

2

Advertisements

One thought on “Upload Images To Server And Display Images As Thumbnail Inside Gridview And Show Popup On Mouseover Using jQuery.

  1. I blog often and I truly thank you for your information.
    This great article has truly peaked my interest. I’m going to book mark your blog and keep checking for new details about once per week. I opted in for your Feed as well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s