HI WELCOME TO SIRIS

HOW TO BIND,UPLOAD,DOWNLOAD,DELETE IMAGE FILES FROM THE GRIDVIEW IN ASP.NET USING SQL SERVER AS A BACK END DATABASE

Leave a Comment
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 inGridView 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>

Note:  I 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(thisthis.GetType(), "Message""alert('Please select the image to upload');",true);
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(thisthis.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(thisthis.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(thisthis.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(thisthis.GetType(), "Message""alert('Error occured : " + ex.Message.ToString() +"');"true);                     
        }      
    }

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

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.