How to upload files and retrieve it on grid view in asp.net c#

Database In sql server 

Table:-




Script for creating table


USE [uploaddata]
GO

/****** Object:  Table [dbo].[fileupload]    Script Date: 04/04/2014 10:00:48 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[fileupload](
          [Id] [int] IDENTITY(1,1) NOT NULL,
          [Name] [nvarchar](50) NULL,
          [Type] [nvarchar](50) NULL,
          [Size] [varbinary](max) NULL,
 CONSTRAINT [PK_fileupload] PRIMARY KEY CLUSTERED
(
          [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO



Source Code:-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="fileuploader.aspx.cs" Inherits="fileuploader" %>
<!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>
   
        <asp:FileUpload ID="FileUpload" runat="server" />
        <br />
        <br />
        <asp:Button ID="btnupload" runat="server" Text="Upload File"


            onclick="btnupload_Click" />
        <br />
        <br />
        <br />
        <asp:GridView ID="gdfile" runat="server" AutoGenerateColumns="False"
            CellPadding="4" ForeColor="#333333" GridLines="None" DataKeyNames="Id">
            <AlternatingRowStyle BackColor="White" />
        <Columns>
                <asp:BoundField DataField="Id" HeaderText="Serial No" />
                <asp:BoundField DataField="Name" HeaderText="File Name" />
                <asp:TemplateField HeaderText="Download">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>

            <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />

        </asp:GridView>
   
    </div>
    </form>
</body>
</html>



Code behind (C#):-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;

public partial class fileuploader : System.Web.UI.Page
{
    string str = "Data Source=NEERAJ-PC; Initial Catalog =uploaddata ;User ID=sa; Password=12345678";


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridviewData();
        }
    }
   
    private void BindGridviewData()
    {
        using (SqlConnection con = new SqlConnection(str))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select * from fileupload";
                cmd.Connection = con;
                con.Open();
                gdfile.DataSource = cmd.ExecuteReader();
                gdfile.DataBind();
                con.Close();
            }
        }
    }
   
   
    protected void lnkDownload_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = sender as LinkButton;
        GridViewRow gdrow = lnkbtn.NamingContainer as GridViewRow;
        int fileid = Convert.ToInt32(gdfile.DataKeys[gdrow.RowIndex].Value.ToString());
  
        using (SqlConnection con = new SqlConnection(str))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select Name,Type,Size from fileupload where Id=@Id";
                cmd.Parameters.AddWithValue("@id", fileid);
                cmd.Connection = con;
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                   Response.ContentType = dr["Type"].ToString();
                    Response.ContentType = dr["Name"].ToString();
                    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + dr["Name"] + "\"");
                    Response.BinaryWrite((byte[])dr["Size"]);
                    Response.End();
                }
            }
        }
    }
    protected void btnupload_Click(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(FileUpload.PostedFile.FileName);
        Stream stream = FileUpload.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(stream);
        Byte[] size = br.ReadBytes((int)stream.Length);
        using (SqlConnection con = new SqlConnection(str))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "insert into fileupload(Name,Type,Size) values(@Name,@Type,@Size)";
                cmd.Parameters.AddWithValue("@Name", filename);
                cmd.Parameters.AddWithValue("@Type", "application");
                cmd.Parameters.AddWithValue("@Size", size);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                BindGridviewData();
            }
        }
 
    }
}



Out –put :-



How to upload files and retrieve it on grid view in asp.net c# How to upload files and retrieve it on grid view  in asp.net c# Reviewed by NEERAJ SRIVASTAVA on 10:12:00 AM Rating: 5

No comments:

Powered by Blogger.