Google How to bind,upload,download,delete image files from the GridView in asp.net using Sql Server as a back end database | Asp.Net,C#.Net,VB.Net,MVC,jQuery,JavaScipt,AJAX,WCF,Sql Server example

How to bind,upload,download,delete image files from the GridView in asp.net using Sql Server as a back end database

Click on image to enlarge
Introduction: In this article I am going to explain with example How to bind, upload, download, and delete image files from the GridView using Sql Server as a Back end database in asp.net with both the C# and VB.Net Languages.
 
Description: So in this article you will learn the following:
  • How to upload image file through FileUpload control and Bind/Load/ Fill in GridView Data control.
  • How to Download and Delete image file from GridView.
  • How to delete the image file permanently from the server folder.
  • How to set multiple DataKeynames in GridView and How to get/read/fetch them in GridView’s RowDeleting event.
  • First of all we need to create the Database in Sql server e.g. “MyDatabase” and in this create a table with the following columns and data types as shown below and name it ”Tb_Images”.
Column
Data Type
Image_Id
Int(Primary key So set Is Identity=True)
Image_Path
varchar(500)
  •    In the web.config file create the connection string to connect our application to the sql server database as:
<connectionStrings>
    <add name="conStr" connectionString="Data Source=lalit;Initial Catalog=MyDataBase;Integrated Security=True"/>
  </connectionStrings>

Note: Replace the Data Source and Initial Catalogue as per your application.

Source Code:
  • First Create a Folder in the root directory of your project and name it “Images”. It is to store the uploaded images and also download and delete icon images that will be used for download and delete uploaded images in GridView. You need to search on Google for the download and delete icons and then place these icons in the Images folder.
  • In the <Form> tag of the design page place a FileUpload control, a Button and a GridView data control and set properties as shown below.
<div>
    <fieldset style="width:350px;">
    <legend>Bind,Upload,Download,Delete Images from GridView</legend>
     <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click"  />
<br />
<br />
<center>
<asp:GridView ID="grdImages" runat="server" AutoGenerateColumns="False" AllowPaging="true"
            EmptyDataText = "No files uploaded" CellPadding="4"
            EnableModelValidation="True" ForeColor="#333333" GridLines="None"
            onrowdeleting="grdImages_RowDeleting" DataKeyNames="Image_Id,Image_Path"
            onpageindexchanging="grdImages_PageIndexChanging" PageSize="5">
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <Columns>  

     <asp:TemplateField HeaderText="Image" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
             <img src='<%#Eval("Image_Path") %>' width="120px" alt="" />             
            </ItemTemplate>
     </asp:TemplateField>          
          
              <asp:TemplateField HeaderText="Download" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
        <ItemTemplate>
            <asp:ImageButton ID="imgDownload" runat="server" ImageUrl="~/Images/DownloadIcon.png" OnClick="imgDownload_Click" ToolTip="Download Image" CausesValidation="false" />
        </ItemTemplate>
        </asp:TemplateField>

         <asp:TemplateField HeaderText="Delete"  HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                 <asp:ImageButton ID="imgDelete" runat="server" CommandName="Delete"  ImageUrl="~/Images/Delete.png" OnClientClick="return confirm('Are you sure you want to delete selected record ?')" ToolTip="Delete" CausesValidation="false"/>
            </ItemTemplate>
         </asp:TemplateField>
    </Columns>
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
</center>
    </fieldset>

NoteI have assigned Image_Id,Image_Path in the DataKeyNames of the gridview above. This way we can add multiple data key names in the gridview.

C#.Net Code to bind,upload,download,delete image files from the GridView in asp.net
  • In the code behind file (.aspx.cs) write the code as:
First include the following namespaces:

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO; 

 Then write the  code as:

    SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string ImgPath = string.Empty;
        string DbImgPath = string.Empty;
      
        try
        {
            if (FileUpload1.HasFile)
            {      
                ImgPath = (Server.MapPath("~/Images/") + Guid.NewGuid() + FileUpload1.FileName);
                FileUpload1.SaveAs(ImgPath);

                DbImgPath = ImgPath.Substring(ImgPath.LastIndexOf("\\"));
                DbImgPath = DbImgPath.Insert(0, "Images");
             
                SqlCommand cmd = new SqlCommand("Insert into Tb_Images (Image_Path) values (@Image_Path)", con);
                cmd.Parameters.AddWithValue("@Image_Path", DbImgPath);
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                cmd.Connection = con;
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                BindGrid();
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Please select the image to upload');", true);
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);                     
        }
        finally
        {
             ImgPath = string.Empty;
             DbImgPath = string.Empty;
             con.Close();         
        }    
    }

    protected void BindGrid()
    {
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();
        try
        {
            SqlCommand cmd = new SqlCommand("select * from Tb_Images", con);
            adp.SelectCommand = cmd;           
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                grdImages.DataSource = dt;
                grdImages.DataBind();
            }
            else
            {
                grdImages.DataSource = null;
                grdImages.DataBind();
            }
        }
        catch(Exception ex)
        {
               ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);                     
        }
        finally
        {
            dt.Clear();
            dt.Dispose();
            adp.Dispose();
        }
    }

    protected void grdImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string physicalPath = string.Empty;
        string imgPath = string.Empty;
        string finalPath = string.Empty;
        try
        {
            //Get the Image_Id from the DataKeyNames
            int imgId = Convert.ToInt32(grdImages.DataKeys[e.RowIndex].Value);
            SqlCommand cmd = new SqlCommand("delete from Tb_Images where Image_Id=@Image_Id", con);
            cmd.Parameters.AddWithValue("@Image_Id", imgId);
            cmd.CommandType = CommandType.Text;
            con.Open();
            cmd.ExecuteNonQuery();
            cmd.Dispose();          
          
           //Get the application physical path of the application
            physicalPath = HttpContext.Current.Request.MapPath(Request.ApplicationPath);
            //Get the Image path from the DataKeyNames
            imgPath = grdImages.DataKeys[e.RowIndex].Values["Image_Path"].ToString();
            //Create the complete path of the image
            finalPath = physicalPath + "\\" + imgPath;

            FileInfo file = new FileInfo(finalPath);
            if (file.Exists)//checking file exsits or not
             {
                 file.Delete();//Delete the file
             }
            BindGrid();
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);                     
        }
        finally
        {
            con.Close();           
            physicalPath = string.Empty;
            imgPath = string.Empty;
            finalPath = string.Empty;
        }     
    }

    protected void imgDownload_Click(object sender, EventArgs e)
    {
        try
        {
            ImageButton imgBtn = sender as ImageButton;
            GridViewRow gvrow = imgBtn.NamingContainer as GridViewRow;
            //Get the Image path from the DataKeyNames          
            string ImgPath = grdImages.DataKeys[gvrow.RowIndex].Values["Image_Path"].ToString();
            Response.AddHeader("Content-Disposition", "attachment;filename=\"" + ImgPath + "\"");
            Response.TransmitFile(Server.MapPath(ImgPath));
            Response.End();
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);                     
        }      
    }

    protected void grdImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdImages.PageIndex = e.NewPageIndex;
        BindGrid();
    }


VB.Net Code to bind,upload,download,delete image files from the GridView in asp.net
  • Design the web page as shown above in the source code section but replace the line
 <asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click"  />

With  <asp:Button ID="btnUpload" runat="server" Text="Upload" />
  • In the code behind file (.aspx.vb) write the code as:
First import the following namespaces: 

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.IO

Then write the code as:

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindGrid()
        End If
    End Sub

    Protected Sub BindGrid()
        Dim dt As New DataTable()
        Dim adp As New SqlDataAdapter()
        Try
            Dim cmd As New SqlCommand("select * from Tb_Images", con)
            adp.SelectCommand = cmd
            adp.Fill(dt)
            If dt.Rows.Count > 0 Then
                grdImages.DataSource = dt
                grdImages.DataBind()
            Else
                grdImages.DataSource = Nothing
                grdImages.DataBind()
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
        Finally
            dt.Clear()
            dt.Dispose()
            adp.Dispose()
        End Try
    End Sub

    Protected Sub btnUpload_Click(sender As Object, e As System.EventArgs) Handles btnUpload.Click
        Dim ImgPath As String = String.Empty
        Dim DbImgPath As String = String.Empty

        Try
            If FileUpload1.HasFile Then
                ImgPath = (Server.MapPath("~/Images/") + Convert.ToString(Guid.NewGuid()) + FileUpload1.FileName)
                FileUpload1.SaveAs(ImgPath)

                DbImgPath = ImgPath.Substring(ImgPath.LastIndexOf("\"))
                DbImgPath = DbImgPath.Insert(0, "Images")

                Dim cmd As New SqlCommand("Insert into Tb_Images (Image_Path) values (@Image_Path)", con)
                cmd.Parameters.AddWithValue("@Image_Path", DbImgPath)
                If con.State = ConnectionState.Closed Then
                    con.Open()
                End If
                cmd.Connection = con
                cmd.ExecuteNonQuery()
                cmd.Dispose()
                BindGrid()
            Else
                ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Please select the image to upload');", True)
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
        Finally
            ImgPath = String.Empty
            DbImgPath = String.Empty
            con.Close()
        End Try
    End Sub

    Protected Sub imgDownload_Click(sender As Object, e As EventArgs)
        Try
            Dim imgBtn As ImageButton = TryCast(sender, ImageButton)
            Dim gvrow As GridViewRow = TryCast(imgBtn.NamingContainer, GridViewRow)
'Get the Image path from the DataKeyNames          
            Dim ImgPath As String = grdImages.DataKeys(gvrow.RowIndex).Values("Image_Path").ToString()
            Response.AddHeader("Content-Disposition", "attachment;filename=""" & ImgPath & """")
            Response.TransmitFile(Server.MapPath(ImgPath))
            Response.[End]()
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
        End Try

    End Sub

    Protected Sub grdImages_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grdImages.RowDeleting
        Dim finalPath As String = String.Empty
        Dim physicalPath As String = String.Empty
        Dim imgPath As String = String.Empty
        Try
            'Get the Image_Id from the DataKeyNames
            Dim imgId As Integer = Convert.ToInt32(grdImages.DataKeys(e.RowIndex).Value)

            Dim cmd As New SqlCommand("delete from Tb_Images where Image_Id=@Image_Id", con)
            cmd.Parameters.AddWithValue("@Image_Id", imgId)
            cmd.CommandType = CommandType.Text
            con.Open()
            cmd.ExecuteNonQuery()
            cmd.Dispose()

            'Get the application physical path of the application
            physicalPath = HttpContext.Current.Request.MapPath(Request.ApplicationPath)
            'Get the Image path from the DataKeyNames
            imgPath = grdImages.DataKeys(e.RowIndex).Values("Image_Path").ToString()
            'Create the complete path of the image
            finalPath = physicalPath & "\" & imgPath

            Dim file As New FileInfo(finalPath)
            'checking file exsits or not
            If file.Exists Then
                'Delete the file
                file.Delete()
            End If
            BindGrid()
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
        Finally
            con.Close()
            finalPath = String.Empty
            physicalPath = String.Empty
            imgPath = String.Empty
        End Try
    End Sub

    Protected Sub grdImages_PageIndexChanging(sender As Object, e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdImages.PageIndexChanging
        grdImages.PageIndex = e.NewPageIndex
        BindGrid()
    End Sub

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."

6 comments :

  1. Replies
    1. thanks for appreciating my articles..keep reading

      Delete
  2. sir I don't understand This line -[ SqlCommand cmd = new SqlCommand("select * from Tb_Images", con);] What is the "con" here and what is data type .
    Please help me sir

    ReplyDelete
  3. Hello rajiul..here con is the object of the sqlconnection to create connection between sql server and asp.net.
    e.g. in this article i have created : SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

    ReplyDelete
  4. Amazing tutorial but Im getting this error "Your string was not in correct format"

    and I dont get this part but everything else I DO!!


    'Get the application physical path of the application
    physicalPath = HttpContext.Current.Request.MapPath(Request.ApplicationPath)
    'Get the Image path from the DataKeyNames
    imgPath = gvDetails.DataKeys(e.RowIndex).Values("FilePath").ToString()
    'Create the complete path of the image
    finalPath = physicalPath & "\" & imgPath

    Specifically I dont know what to change in this Line

    finalPath = physicalPath & "\" & imgPath

    ReplyDelete
  5. I have submitted my question but it doest appear in the comment box?? Why??

    ReplyDelete

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..