store and open pdf file to datagidview
- Kareninstructor
- Friday, November 10, 2017 12:28 PM
- 10
store and open pdf file to datagridview
Use the following code to save images to the database with the save button, save well, delete images and delete well
what I want Save any file to the access database2007 - and reopen the file
'connection code
'Public con As New OleDb.OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=" & Application.StartupPath & "\Database1.accdb;Jet OLEDB:Database Password=2240") 'Dim DataSet1 As New DataSet ' Dim BindingSource1 As BindingSource 'Dim BindingSource2 As BindingSource ' Dim DataAdapter1 As New OleDbDataAdapter
Private Sub savimage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles savimage.Click ' save If BindingSource1.Count = 0 Then Beep() : Exit Sub Try If PictureBox1.Image IsNot Nothing Then If MsgBox(" change image " & " ؟ ", MsgBoxStyle.Exclamation + MsgBoxStyle.MsgBoxRight + MsgBoxStyle.OkCancel, "استبدال صورة") = MsgBoxResult.Cancel Then Exit Sub Else If MsgBox(" add new image " & Label2.Text & " ؟ ", MsgBoxStyle.Exclamation + MsgBoxStyle.MsgBoxRight + MsgBoxStyle.OkCancel, "ادراج صورة") = MsgBoxResult.Cancel Then Exit Sub End If Application.DoEvents() Dim OFG As New OpenFileDialog OFG.Filter = "Image Files (*.bmp;*.jpg;*.jpeg;*.GIF)|*.bmp;*.jpg;*.jpeg;*.GIF|" + _ "PNG files (*.png)|*.png|text files (*.text)|*.txt|doc files (*.doc)|*.doc|pdf files (*.pdf)|*.pdf" '"Files(*.jpg)|*.jpg|Files(*.gif)|*.gif|Files(*.bmp)|*.bmp|Files(*.png)|*.png" OFG.Title = "add image" OFG.FileName = "" OFG.FilterIndex = 3 If OFG.ShowDialog() = Windows.Forms.DialogResult.OK Then Dim fs As IO.FileStream = New IO.FileStream(OFG.FileName, IO.FileMode.Open, IO.FileAccess.Read) Dim LoadImage As Image = Image.FromStream(fs) fs.Close() Dim Stream As New IO.MemoryStream() Dim NewBitmap As New Bitmap(LoadImage, 200, 225) NewBitmap.Save(Stream, System.Drawing.Imaging.ImageFormat.Jpeg) Application.DoEvents() BindingSource1.EndEdit() DataAdapter1.Update(DataSet1.Tables("purch_tb")) DataSet1.Tables("purch_tb").Rows(BindingSource1.Position).Item("pic_prod") = Stream.ToArray Stream.Close() BindingSource1.EndEdit() DataAdapter1.Update(DataSet1.Tables("purch_tb")) Application.DoEvents() MsgBox("image save", MsgBoxStyle.MsgBoxRight + MsgBoxStyle.Information, "succ ") End If Catch ex As Exception MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Private Sub deletimage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletimage.Click 'delete image Try If PictureBox1.Image Is Nothing Then Beep() : MsgBox("no image found") : Exit Sub If MsgBox(" contenu delete image" & " ؟ ", MsgBoxStyle.Exclamation + MsgBoxStyle.MsgBoxRight + MsgBoxStyle.OkCancel, "delete image") = MsgBoxResult.Cancel Then Exit Sub PictureBox1.Image = Nothing BindingSource1.EndEdit() DataAdapter1.Update(DataSet1.Tables("purch_tb")) MsgBox("image was delete", MsgBoxStyle.MsgBoxRight + MsgBoxStyle.Information, "succ ") Catch ex As Exception MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub
10 Answers
Below is a working example of adding, removing, and restoring pdf (or other) files to an access database. I started with a blank access database with 2 fields/columns as shown below and named the Table as FilesTable for this example. And, yes i am using a very old version of MS Access so, yours may look a little different.

After creating the empty database file, you can test the example below by creating a new Windows Form project and adding 1 DataGridView and 3 Buttons on the form. The 3 buttons are named Button_AddNewFile, Button_RemoveSelectedFile, and Button_RestoreSelectedFile. Then you can use the code below. You will have to change the file path and name to the path and name of your database file you created for this example.
Imports System.Data.OleDb
Public Class Form1
Private dbConn As OleDbConnection
Private dset As New DataSet
Private dataAdapter As OleDbDataAdapter
Private bindingSrc As BindingSource
Private cmndBuilder As OleDbCommandBuilder
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dataFile As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "FileDatabase.mdb")
dbConn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" & dataFile)
dataAdapter = New OleDbDataAdapter("Select * From FilesTable", dbConn)
dbConn.Open()
dataAdapter.Fill(dset, "FilesTable")
dbConn.Close()
cmndBuilder = New OleDbCommandBuilder(dataAdapter)
cmndBuilder.QuotePrefix = "["
cmndBuilder.QuoteSuffix = "]"
bindingSrc = New BindingSource
bindingSrc.DataSource = dset.Tables("FilesTable")
With DataGridView1
.AllowUserToAddRows = False
.ReadOnly = True
.RowHeadersVisible = False
.MultiSelect = False
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.DataSource = bindingSrc
.Columns("File_Bytes").Visible = False 'Hide the column that holds the byte array for the file. Throws an exception if you don't.
.Columns("File_Name").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
.Columns("File_Name").HeaderCell.Value = .Columns("File_Name").HeaderCell.Value.ToString.Replace("_", " ")
End With
End Sub
Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
If dbConn.State <> ConnectionState.Closed Then dbConn.Close()
dbConn.Dispose()
dataAdapter.Dispose()
bindingSrc.Dispose()
dset.Dispose()
cmndBuilder.Dispose()
End Sub
Private Sub Button_AddNewFile_Click(sender As Object, e As EventArgs) Handles Button_AddNewFile.Click
Using ofd As New OpenFileDialog
ofd.Filter = "Pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*"
ofd.FilterIndex = 1
If ofd.ShowDialog = DialogResult.OK Then
If bindingSrc.Find("File_Name", ofd.FileName) = -1 Then
Dim drv As DataRowView = CType(bindingSrc.AddNew(), DataRowView)
drv("File_Name") = ofd.FileName
drv("File_Bytes") = IO.File.ReadAllBytes(ofd.FileName)
bindingSrc.EndEdit()
dbConn.Open()
dataAdapter.Update(dset.Tables("FilesTable"))
dbConn.Close()
Else
MessageBox.Show("The database already contains the selected file.", "Add Files...")
End If
End If
End Using
End Sub
Private Sub Button_RemoveSelectedFile_Click(sender As Object, e As EventArgs) Handles Button_RemoveSelectedFile.Click
If DataGridView1.SelectedRows.Count > 0 Then
Dim dr As DialogResult = MessageBox.Show("Are you sure you want to delete the selected file from the database?", "Remove File...", MessageBoxButtons.YesNo)
If dr = DialogResult.Yes Then
bindingSrc.RemoveCurrent()
dbConn.Open()
dataAdapter.Update(dset.Tables("FilesTable"))
dbConn.Close()
End If
End If
End Sub
Private Sub Button_RestoreSelectedFile_Click(sender As Object, e As EventArgs) Handles Button_RestoreSelectedFile.Click
If DataGridView1.SelectedRows.Count > 0 Then
Dim drv As DataRowView = CType(bindingSrc.Current, DataRowView)
Dim filename As String = drv("File_Name").ToString
If IO.File.Exists(filename) Then
Dim dr As DialogResult = MessageBox.Show("The selected file already exists. Do you want to overwrite the existing file?", "Restore File...", MessageBoxButtons.YesNo)
If dr = DialogResult.No Then Exit Sub
End If
IO.File.WriteAllBytes(filename, CType(drv("File_Bytes"), Byte()))
MessageBox.Show("File Restored To..." & vbNewLine & filename, "Restore File...")
End If
End Sub
End Class
Here is how i have set up the form. I already added a few pdf files.

Hopefully it will help you get going. 8)
IronRazerz
Saturday, November 11, 2017 9:28 PM
ahmeddc
Saturday, November 11, 2017 11:42 PM
open file from datagridview
Is there a direct way from inside the Data Grid
'open file
On Error Resume Next
If DataGridView1.SelectedRows.Count > 0 Then
Dim drv As DataRowView = CType(bindingSrc.Current, DataRowView)
Dim filename As String = drv("File_Name").ToString
If IO.File.Exists(filename) Then
Dim dr As DialogResult = MessageBox.Show("The selected file already exists. Do you want to overwrite the existing file?", "Restore File...", MessageBoxButtons.YesNo)
If dr = DialogResult.No Then Exit Sub
End If
IO.File.WriteAllBytes(filename, CType(drv("File_Bytes"), Byte()))
Process.Start(filename) ' open file
MessageBox.Show("File Restored To..." & vbNewLine & filename, "Restore File...")
End If
ahmeddc
Sunday, November 12, 2017 12:09 AM
A direct way to do what? I don't understand what you are asking.
The file is saved to the database as a Byte Array which must be written back to the hard drive as the same type of file, a pdf in this case, before you can use or open the file.
PS - Get rid of the On Error vb6 leftovers. If you need to handle errors in Vb.Net, you should use a Try-Catch.
IronRazerz
Sunday, November 12, 2017 12:53 AM
I thought it was like the pictures where I gave the picture to Picture Box and then it shows up I am a sinner excuse me Let's go beyond this I want to edit this code where I do not add a new row But adds the file to the selected row only
I deleted the part of the new row appearance but did not add the file to the row that was selected
Using ofd As New OpenFileDialog
ofd.Filter = "Pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*"
ofd.FilterIndex = 1
If ofd.ShowDialog = DialogResult.OK Then
If bindingSrc.Find("File_Name", ofd.FileName) = -1 Then
Dim drv As DataRowView '= CType(bindingSrc.AddNew(), DataRowView) ' delete = to end
drv("File_Name") = ofd.FileName
drv("File_Bytes") = IO.File.ReadAllBytes(ofd.FileName)
bindingSrc.EndEdit()
dbConn.Open()
dataAdapter.Update(dset.Tables("FilesTable"))
dbConn.Close()
Else
MessageBox.Show("The database already contains the selected file.", "Add Files...")
End If
End If
End Using
ahmeddc
Sunday, November 12, 2017 3:17 AM
Hello,
The following shows insert and extraction, not pretty but does the jobs.

Data class (I never code data operations directly in a form, only call to a class such as this)
Imports System.Data.OleDb
Public Class Operations
Private Builder As New OleDbConnectionStringBuilder With
{
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database.accdb"),
.Provider = "Microsoft.ACE.OLEDB.12.0"
}
Public Property HasException As Boolean
Public Property Exception As Exception
''' <summary>
''' Return all rows, hide primary key
''' </summary>
''' <returns></returns>
Public Function Read() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText = "SELECT Identifier, FileName, Comment FROM Table1"
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
dt.Columns("Identifier").ColumnMapping = MappingType.Hidden
Return dt
End Function
''' <summary>
''' Insert an existing file
''' </summary>
''' <param name="pFileName">full path and file name</param>
''' <param name="pNewIndentfier">Will contain new primary key after record has been inserted</param>
''' <returns></returns>
Public Function Insert(ByVal pFileName As String, ByRef pNewIndentfier As Integer) As Boolean
Dim success As Boolean = False
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
Dim dr As OleDbDataReader = Nothing
Dim FileStream As IO.FileStream
Dim Reader As IO.BinaryReader = Nothing
Dim Data() As Byte = Nothing
FileStream = New IO.FileStream(pFileName, IO.FileMode.Open, IO.FileAccess.Read)
Reader = New IO.BinaryReader(FileStream)
Data = Reader.ReadBytes(CInt(FileStream.Length))
cn.Open()
cmd.CommandText = "INSERT INTO Table1 (FileName, Contents,Comment) VALUES(@FileName,@Contents,@Comment)"
cmd.Connection = cn
cmd.Parameters.Add("@FileName", OleDbType.WChar)
cmd.Parameters(0).Value = IO.Path.GetFileName(pFileName)
cmd.Parameters.Add("@Contents", OleDbType.LongVarBinary)
cmd.Parameters.AddWithValue("@Comment", Now.ToShortDateString)
cmd.Parameters(1).Value = Data
'
' insert record
'
success = (cmd.ExecuteNonQuery() = 1)
'
' get newly added record's primary key
'
cmd.CommandText = "Select @@Identity"
pNewIndentfier = CInt(cmd.ExecuteScalar)
End Using
End Using
Catch ex As Exception
HasException = True
Exception = ex
success = False
End Try
Return success
End Function
''' <summary>
''' Extract file by primary key
''' </summary>
''' <param name="pIdentifier">Primary key to locate record by</param>
''' <param name="pFileName">Full path and file name to extract binary data too</param>
''' <returns></returns>
''' <remarks>
''' Common method to know the primary key is from first reading data and returning
''' at least the primary key
''' Example
''' SELECT Identifier FROM Table1 WHERE FileName = @FileName
''' Where @FileName contains the name of the file w/o the path
''' </remarks>
Public Function Extract(ByVal pIdentifier As Integer, ByVal pFileName As String) As Boolean
Dim success As Boolean = False
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText = "SELECT Contents FROM Table1 Where Identifier=@Identifier"
cmd.Parameters.AddWithValue("@Identifier", pIdentifier)
Dim dr As OleDbDataReader = Nothing
Dim FileStream As IO.FileStream
Dim Reader As OleDbDataReader
Dim Data() As Byte = Nothing
Dim Writer As IO.BinaryWriter = Nothing
Dim bufferSize As Integer = 1000
Dim buffer(bufferSize - 1) As Byte
Dim startIndex As Long = 0
Dim numberOfBytes As Long = 0
cn.Open()
Reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
Reader.Read()
FileStream = New IO.FileStream(pFileName, IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
Writer = New IO.BinaryWriter(FileStream)
Do
numberOfBytes = Reader.GetBytes(0, startIndex, buffer, 0, bufferSize)
If numberOfBytes = 0 Then
Exit Do
End If
Writer.Write(buffer, 0, CInt(Fix(numberOfBytes)))
startIndex += numberOfBytes
Loop While True
Writer.Flush()
If Writer IsNot Nothing Then
Writer.Close()
End If
If FileStream IsNot Nothing Then
FileStream.Close()
End If
If Reader IsNot Nothing Then
Reader.Close()
End If
success = True
End Using
End Using
Catch ex As Exception
HasException = True
Exception = ex
success = False
End Try
Return success
End Function
End Class
Form code
Imports BackEnd
''' <summary>
''' To generate records I used insertFileName and extractFileName to do the work.
''' Currently Button1 is still setup for a file already inserted so if used again
''' without changing anything it will be inserted again.
''' </summary>
Public Class Form1
WithEvents bsData As New BindingSource
Private insertFileName As String = IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Document.docx")
Private extractFileName As String = IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Extracted", "Document.docx")
Private documentPrimaryKey As Integer = 0
Private Sub insertFile_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ops As New Operations
Dim NewIndentfier As Integer = 0
If ops.Insert(insertFileName, NewIndentfier) Then
Button1.Enabled = False
documentPrimaryKey = NewIndentfier
MessageBox.Show($"Inserted document, new key is {NewIndentfier}")
Else
If ops.HasException Then
MessageBox.Show($"{ops.Exception.Message}")
End If
End If
End Sub
Private Sub extractFile_Click(sender As Object, e As EventArgs) Handles Button2.Click
If documentPrimaryKey < 1 Then
MessageBox.Show("Please add the document!!!")
Exit Sub
End If
Dim ops As New Operations
If ops.Extract(documentPrimaryKey, extractFileName) Then
MessageBox.Show($"{extractFileName} is ready")
Button2.Enabled = False
Else
If ops.HasException Then
MessageBox.Show($"{ops.Exception.Message}")
End If
End If
End Sub
''' <summary>
''' Read in data
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If IO.File.Exists(extractFileName) Then
IO.File.Delete(extractFileName)
End If
Dim ops As New Operations
bsData.DataSource = ops.Read
DataGridView1.DataSource = bsData
Button3.Enabled = bsData.Count > 0
End Sub
Private Sub getCurrentRowInfo_Click(sender As Object, e As EventArgs) Handles Button3.Click
If bsData.Current IsNot Nothing Then
Dim currentRow As DataRow = CType(bsData.Current, DataRowView).Row
MessageBox.Show($"Use this id to get data {currentRow.Field(Of Integer)("Identifier")} FileName: {currentRow.Field(Of String)("FileName")}")
End If
End Sub
End Class
I set up two queries, one truncates the table, the other resets the primary key.


Kareninstructor
Sunday, November 12, 2017 3:56 AM
I don't know of any Controls or 3rd party libraries that can take a byte array of a pdf file, convert it, and display it like you can with an image. Not saying there is not one out there though, i never looked for one.
So, you want to select an existing row and change it to a newly selected file?
If that is what you want to do, then change the line that added the new row so it gets the Current selected item from the BindingSource and casts it to a DataRowView as shown below... That would be all there is to it. The rest of the code in the sub should stay as it is. That would update the selected row to the new file.
Dim drv As DataRowView = CType(bindingSrc.Current, DataRowView)
IronRazerz
Sunday, November 12, 2017 4:01 AM
ahmeddc
Sunday, November 12, 2017 4:09 AM
After posting I decided to write up a code sample on MSDN, thought you might want to check this out. The FileName and Comment can be edited directly in the DataGridView and saved no different from if you were in MS-Access editing data.
https://code.msdn.microsoft.com/MS-Access-working-with-00e96d88


Kareninstructor
Sunday, November 12, 2017 4:40 PM
store and open pdf file to datagidview - MSDN
store and open pdf file to datagridview. Use the following code to save images to the database with the save button, save well, delete images This article explains how to store and view PDF files in a GridView in ASP.NET.
How do I open pdf file from datagridview..
Thank you for the kind info but its requirement from authority person. Now my files are in server. I Just brought file string to database and store and open pdf file to datagridview . Use the following code to save images to the database with the save button, save well, delete images and delete well. what I want Save any file to the access database2007 - and reopen the file 'connection code
Store and View PDF Files in a GridView
This article explains how to store and view PDF files in a GridView in ASP Next Recommended Article How to Open PDF Files in Web Brower In this code example, we will learn how to export DataGridView data to a pdf file and save that in a folder using C# code. In this program, first, we have to get connected to the database and fetch data from the DB and show it in the Data GridView like the below image.

Kareninstructor
Friday, November 10, 2017 12:37 PM