File Upload in Gridview ASP.NET

Category > ASP.NET || Published on : Monday, December 8, 2014 || Views: 11965 || File Upload in Gridview ASP.NET File Upload Gridview ASP.NET example


In this tutorial, we are goint to learn how to Upload file in Gridview ASP.NET, So lets starts the coding.

Step 1: Create the Table in MsSQL Server with the following sql script(SQLScript.txt)

CREATE TABLE [dbo].[UploadDocumentDemo](
    [empid] [varchar](10) NULL,
    [name] [varchar](100) NULL,
    [photo_path] [varchar](100) NULL
) ON [PRIMARY]

(This script is also present in the Demo Source Codes Winrar file)

Step 2: Create a ASP.NET empty Web Application.

Step 3: Create a webform “Default.aspx” and write the following codes.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" EnableEventValidation="false" Inherits="_Default" %>

"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
"http://www.w3.org/1999/xhtml">
"server">
    


    "form1" runat="server">
    
"gvUpload" runat="server" AutoGenerateColumns="false" ShowFooter="true" EmptyDataText="No records found"> "Employee-ID"> "lblEmpID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "empid") %>'> "txtEmpID" runat="server"> "Name"> "lblName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "name") %>'> "txtName" runat="server"> "Photo"> "imgPhoto" runat="server" Width="100px" Height="120px" ImageUrl='<%#DataBinder.Eval(Container.DataItem, "photo_path") %>' /> "fUpload" runat="server" /> "btnUpload" runat="server" Text="Upload" OnClick="btnUpload_OnClick" /> "lblMsg" runat="server">


Step 4: Write the  following Code in Code Behind file of the "Default.aspx". also change the connection string as based on your system requirements.

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;
using System.Configuration;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=test;Integrated Security=True");
 
    protected void Page_Load(object sender, EventArgs e)
    {        
        if (!IsPostBack)
        {            
            BindGrid();
        }
    }

    protected void BindGrid()
    {
        DataSet ds = new DataSet();
        DataTable FromTable = new DataTable();
        conn.Open();
        string cmdstr = "Select * from UploadDocumentDemo";
        SqlCommand cmd = new SqlCommand(cmdstr, conn);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(ds);
        cmd.ExecuteNonQuery();
        FromTable = ds.Tables[0];

        if (FromTable.Rows.Count > 0)
        {
            gvUpload.DataSource = FromTable;
            gvUpload.DataBind();
        }
        else
        {
            FromTable.Rows.Add(FromTable.NewRow());
            gvUpload.DataSource = FromTable;
            gvUpload.DataBind();
            int TotalColumns = gvUpload.Rows[0].Cells.Count;
            gvUpload.Rows[0].Cells.Clear();
            gvUpload.Rows[0].Cells.Add(new TableCell());
            gvUpload.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            gvUpload.Rows[0].Cells[0].Text = "No records Found";
        }
        ds.Dispose();
        conn.Close();
      
    }

    protected void btnUpload_OnClick(object sender, EventArgs e)
    {                 
            TextBox txtEmpID = (TextBox)gvUpload.FooterRow.FindControl("txtEmpID");
            TextBox txtName = (TextBox)gvUpload.FooterRow.FindControl("txtName");
            FileUpload fuploadFile = (FileUpload)gvUpload.FooterRow.FindControl("fUpload");
            Button btnUpload = (Button)gvUpload.FooterRow.FindControl("btnUpload");

            if (fuploadFile.HasFile)
            {                
                string fileName = fuploadFile.FileName;
                string exten = Path.GetExtension(fileName);  

                //check that the file is of the permitted file type                

                exten = exten.ToLower();

                string[] acceptedFileTypes = new string[4];
             
                acceptedFileTypes[0] = ".jpg";
                acceptedFileTypes[1] = ".jpeg";
                acceptedFileTypes[2] = ".gif";
                acceptedFileTypes[3] = ".png";                
                
                bool acceptFile = false;
               
                for (int i = 0; i <= 3; i++)
                {
                    if (exten == acceptedFileTypes[i])
                    {
                       
                        acceptFile = true;
                    }
                }

                if (!acceptFile)
                {
                    lblMsg.Text = "The file you are trying to upload is not a permitted file type!";
                }
                else
                {
                    //upload the file onto the server
                    fuploadFile.SaveAs(Server.MapPath("~/Document/" + fileName));

                    conn.Open();
                    string cmdstr = "insert into UploadDocumentDemo(empid,name,photo_path) values(@empid,@name,@photo)";
                    SqlCommand cmd = new SqlCommand(cmdstr, conn);
                    cmd.Parameters.AddWithValue("@empid", txtEmpID.Text);
                    cmd.Parameters.AddWithValue("@name", txtName.Text);
                    cmd.Parameters.AddWithValue("@photo", "Document/"+fileName);
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    BindGrid();
                }
            }
        
    }


}

Step 5:  Run the application or press the F5 Key on the keyboard. Now you will upload files with in the Gridview

Conclusion:-
so In this tutorial, we have learned How to File Upload in Gridview ASP.NET with Asp.Net C# with Example. Happy Coding!!!!

Note: For Working Demo, you can download the Article source code below.

Download Source Codes