Hi kankon,
Using the below article i have created the example.
Check this example. Now please take its reference and correct your code.
HTML
<asp:FileUpload ID="FileUpload2" runat="server" />
<asp:Button ID="AddUsers" runat="server" Text="Insert" OnClick="Insert" />
<hr />
<asp:GridView runat="server" ID="gvFiles" AutoGenerateColumns="false" AutoGenerateDeleteButton="true"
AutoGenerateEditButton="true" OnRowCancelingEdit="OnRowCancelingEdit" OnRowDeleting="OnRowDeleting"
OnRowEditing="OnRowEditing" OnRowUpdating="OnRowUpdating" DataKeyNames="Id">
<Columns>
<asp:BoundField DataField="Name" HeaderText="File Name"></asp:BoundField>
<asp:TemplateField HeaderText="Files">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="fuFile" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Code
C#
string str = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindGridView();
}
}
protected void Insert(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload2.PostedFile.FileName);
string contentType = FileUpload2.PostedFile.ContentType;
using (Stream fs = FileUpload2.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO tblFiles VALUES(@Name,@ContentType,@Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", filename);
cmd.Parameters.AddWithValue("@ContentType", contentType);
cmd.Parameters.AddWithValue("@Data", bytes);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
}
}
protected void OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvFiles.EditIndex = -1;
BindGridView();
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
gvFiles.EditIndex = e.NewEditIndex;
BindGridView();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
BindGridView();
}
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvFiles.Rows[e.RowIndex];
int id = Convert.ToInt32(gvFiles.DataKeys[e.RowIndex].Values[0]);
FileUpload FileUpload1 = row.FindControl("fuFile") as FileUpload;
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = "";
byte[] bytes = null;
if (FileUpload1.HasFile)
{
contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
bytes = br.ReadBytes((Int32)fs.Length);
}
}
}
using (SqlConnection con = new SqlConnection(str))
{
string query = "UPDATE tblFiles SET Name = @Name,ContentType = @ContentType,Data=@Data WHERE id = @Id";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Id", id);
cmd.Parameters.AddWithValue("@Name", fileName);
cmd.Parameters.AddWithValue("@ContentType", contentType);
cmd.Parameters.AddWithValue("@Data", bytes == null ? new byte[] { } : bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
gvFiles.EditIndex = -1;
BindGridView();
}
protected void DownloadFile(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Name, Data, ContentType from tblFiles where Id=@Id";
cmd.Parameters.AddWithValue("@Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Name"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
private void BindGridView()
{
using (SqlConnection con = new SqlConnection(str))
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblFiles", con))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
gvFiles.DataSource = dt;
gvFiles.DataBind();
}
}
}
}
VB.Net
Private str As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
BindGridView()
End If
End Sub
Protected Sub Insert(ByVal sender As Object, ByVal e As EventArgs)
Dim filename As String = Path.GetFileName(FileUpload2.PostedFile.FileName)
Dim contentType As String = FileUpload2.PostedFile.ContentType
Using fs As Stream = FileUpload2.PostedFile.InputStream
Using br As BinaryReader = New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(CType(fs.Length, Int32))
Dim constr As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Dim query As String = "INSERT INTO tblFiles VALUES(@Name,@ContentType,@Data)"
Using cmd As SqlCommand = New SqlCommand(query)
cmd.Connection = con
cmd.Parameters.AddWithValue("@Name", filename)
cmd.Parameters.AddWithValue("@ContentType", contentType)
cmd.Parameters.AddWithValue("@Data", bytes)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Response.Redirect(Request.Url.AbsoluteUri)
End Using
End Using
End Using
End Using
End Sub
Protected Sub OnRowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
gvFiles.EditIndex = -1
BindGridView()
End Sub
Protected Sub OnRowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
gvFiles.EditIndex = e.NewEditIndex
BindGridView()
End Sub
Protected Sub OnRowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
BindGridView()
End Sub
Protected Sub OnRowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim row As GridViewRow = gvFiles.Rows(e.RowIndex)
Dim id As Integer = Convert.ToInt32(gvFiles.DataKeys(e.RowIndex).Values(0))
Dim FileUpload1 As FileUpload = TryCast(row.FindControl("fuFile"), FileUpload)
Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim contentType As String = ""
Dim bytes As Byte() = Nothing
If FileUpload1.HasFile Then
contentType = FileUpload1.PostedFile.ContentType
Using fs As Stream = FileUpload1.PostedFile.InputStream
Using br As BinaryReader = New BinaryReader(fs)
bytes = br.ReadBytes(CType(fs.Length, Int32))
End Using
End Using
End If
Using con As SqlConnection = New SqlConnection(str)
Dim query As String = "UPDATE tblFiles SET Name = @Name,ContentType = @ContentType,Data=@Data WHERE id = @Id"
Using cmd As SqlCommand = New SqlCommand(query)
cmd.Connection = con
cmd.Parameters.AddWithValue("@Id", id)
cmd.Parameters.AddWithValue("@Name", fileName)
cmd.Parameters.AddWithValue("@ContentType", contentType)
cmd.Parameters.AddWithValue("@Data", If(bytes Is Nothing, New Byte() {}, bytes))
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
gvFiles.EditIndex = -1
BindGridView()
End Sub
Protected Sub DownloadFile(ByVal sender As Object, ByVal e As EventArgs)
Dim id As Integer = Integer.Parse((TryCast(sender, LinkButton)).CommandArgument)
Dim bytes As Byte()
Dim fileName, contentType As String
Using con As SqlConnection = New SqlConnection(str)
Using cmd As SqlCommand = New SqlCommand()
cmd.CommandText = "SELECT Name, Data, ContentType from tblFiles where Id=@Id"
cmd.Parameters.AddWithValue("@Id", id)
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
sdr.Read()
bytes = CType(sdr("Data"), Byte())
contentType = sdr("ContentType").ToString()
fileName = sdr("Name").ToString()
End Using
con.Close()
End Using
End Using
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = contentType
Response.AppendHeader("Content-Disposition", "attachment; filename=" & fileName)
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End Sub
Private Sub BindGridView()
Using con As SqlConnection = New SqlConnection(str)
Using da As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM tblFiles", con)
Using dt As DataTable = New DataTable()
da.Fill(dt)
gvFiles.DataSource = dt
gvFiles.DataBind()
End Using
End Using
End Using
End Sub