Thursday 4 July 2013

working File Upload in Gridview ASP.NET

File Upload in Gridview ASP.NET

Introduction:
            In this article I’m going to explain how to use file upload control in grid view for uploading images or files to the server.
Description:
          The FileUpload control allows you to provide users with a way to send a file from their computer to the server. The control is useful for allowing users to upload images, text files or other files.
           Here I’ll show you how use file upload control in gridview to upload the images or files to the server and I’m going to display that files in gridview.
          So we have to create one table for storing basic details of employee including employee’s photo
Table Design:
                        Column Name
                            Data type
empid
varchar(50)
name
varchar(100)
photo_path
varchar(100)

Create table script:
CREATE TABLE [dbo].[UploadDoc](
     [empid] [varchar](10) NULL,
     [name] [varchar](100) NULL,
     [photo_path] [varchar](100) NULL
) ON [PRIMARY]





.ASPX CODE:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="USER_Profile_UPload.aspx.cs" Inherits="USER_Profile_UPload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div>
<asp:GridView ID="gvUpload" runat="server" AutoGenerateColumns="false" ShowFooter="true">
<Columns>
    <asp:TemplateField HeaderText="S.No." ItemStyle-HorizontalAlign="Center">
        <ItemTemplate>
            <%#Container.DataItemIndex+1%>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Employee-ID">
        <ItemTemplate>
            <asp:Label ID="lblEmpID" runat="server" Text='<%#DataBinder.
                              Eval(Container.DataItem, "empid") %>'></asp:Label>
        </ItemTemplate>
        <FooterTemplate>
            <asp:TextBox ID="txtEmpID" runat="server"></asp:TextBox>
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Name">
        <ItemTemplate>
            <asp:Label ID="lblName" runat="server" Text='<%#DataBinder.
                              Eval(Container.DataItem, "name") %>'></asp:Label>
        </ItemTemplate>
        <FooterTemplate>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Photo">
    <ItemTemplate>
         <asp:Image ID="imgPhoto" runat="server" Width="100px" Height="120px"
                 ImageUrl='<%#DataBinder.Eval(Container.DataItem, "photo_path") %>' />
    </ItemTemplate>
    <FooterTemplate>
         <asp:FileUpload ID="fUpload" runat="server" />
    </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
        <FooterTemplate>
            <asp:Button ID="btnUpload" runat="server" Text="Upload"
                                           OnClick="btnUpload_OnClick" />
        </FooterTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblMsg" runat="server"></asp:Label>
</div>
    </div>
    </form>
</body>
</html>



.CS CODE:

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.Data.SqlClient;
using System.IO;
using System.Configuration;



public partial class USER_Profile_UPload : System.Web.UI.Page
{
    string Str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }


    }
    protected void BindGrid()
    {
        DataSet ds = new DataSet();
        DataTable FromTable = new DataTable();
        SqlConnection conn = new SqlConnection(Str);
        conn.Open();
        string cmdstr = "Select * from UploadDoc";
        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);
            //here we have to restrict 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));
                SqlConnection conn = new SqlConnection(Str);
                conn.Open();
                string cmdstr = "insert into UploadDoc(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();
            }
        }

    }
}

No comments:

Post a Comment