Import Excel file to Datagridview Vb.net - vb.net

Is there a way to display the excel file directly to the Datagridview without the combobox or choosing the sheets to display? Since my excel file contains only 1 sheet.
Dim tables As DataTableCollection
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Using ofd As OpenFileDialog = New OpenFileDialog() With {.Filter = "Excel 97-2003 Workbook|*.xls|Excel Workbook|*.xlsx"}
If ofd.ShowDialog() = DialogResult.OK Then
txtFileName.Text = ofd.FileName
Using stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read)
Using reader As IExcelDataReader = ExcelReaderFactory.CreateReader(stream)
Dim result As DataSet = reader.AsDataSet(New ExcelDataSetConfiguration() With {
.ConfigureDataTable = Function(__) New ExcelDataTableConfiguration() With {
.UseHeaderRow = True}})
tables = result.Tables
cboSheet.Items.Clear()
For Each table As DataTable In tables
cboSheet.Items.Add(table.TableName)
Next
End Using
End Using
End If
End Using
End Sub
Private Sub cboSheet_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSheet.SelectedIndexChanged
Dim dt As DataTable = tables(cboSheet.SelectedItem.ToString())
DataGridView1.DataSource = dt
End Sub

Related

No value given for one or more required parameters while trying to access a picture file from an Acces database using VB.net

Im doing a school project. and I was testing a login form for my app. I'm trying separately from my login form and a profile pic form. I have successfully managed to save the image to the access database but I have had quite a few problems trying to display it on a textbox on my form.
This is the whole app code:
Imports System.Data.OleDb
Imports System.IO
Public Class Form2
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\BD de imagenes\BD de imagenes\DBImagenes.mdb")
Dim cmd As New OleDbCommand
Dim sql As String
Dim da As New OleDb.OleDbDataAdapter
Dim result As Integer
Private Sub saveimage(sql As String)
Try
Dim arrimage() As Byte
Dim mstream As New System.IO.MemoryStream
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Png)
arrimage = mstream.GetBuffer()
Dim Filesize As UInt32
Filesize = mstream.Length
mstream.Close()
con.Open()
cmd = New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("#Imagen", arrimage)
.Parameters.Add("#Nombre", OleDbType.VarChar).Value = TextBox1.Text
.ExecuteNonQuery()
End With
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
'End Try
Public conex As New OleDbConnection()
Public Sub conexion()
conex.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\BD de imagenes\BD de imagenes\DBImagenes.mdb"
conex.Open()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles BTNGuardar.Click
sql = "Insert into TBImg (Imagen, Nombre) Values (#Imagen, #Nombre)"
'sql = "Insert into TBImg (Imagen) Values (#Imagen)"
saveimage(sql)
MsgBox("Image has been saved in the database")
End Sub
Private Sub BtnExaminar_Click(sender As Object, e As EventArgs) Handles BtnExaminar.Click
OpenFileDialog1.Filter = "Imagenes JPG|*.jpg|Imagenes PNG|*.png"
OpenFileDialog1.RestoreDirectory = True
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
Try
With OpenFileDialog1
'CHECK THE SELECTED FILE IF IT EXIST OTHERWISE THE DIALOG BOX WILL DISPLAY A WARNING.
.CheckFileExists = True
'CHECK THE SELECTED PATH IF IT EXIST OTHERWISE THE DIALOG BOX WILL DISPLAY A WARNING.
.CheckPathExists = True
'GET AND SET THE DEFAULT EXTENSION
.DefaultExt = "jpg"
'RETURN THE FILE LINKED TO THE LNK FILE
.DereferenceLinks = True
'SET THE FILE NAME TO EMPTY
.FileName = ""
'FILTERING THE FILES
.Filter = "(*.jpg)|*.jpg|(*.png)|*.png|(*.jpg)|*.jpg|All files|*.*"
'SET THIS FOR ONE FILE SELECTION ONLY.
.Multiselect = False
'SET THIS TO PUT THE CURRENT FOLDER BACK TO WHERE IT HAS STARTED.
.RestoreDirectory = True
'SET THE TITLE OF THE DIALOG BOX.
.Title = "Select a file to open"
'ACCEPT ONLY THE VALID WIN32 FILE NAMES.
.ValidateNames = True
If .ShowDialog = DialogResult.OK Then
Try
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
Catch fileException As Exception
Throw fileException
End Try
End If
End With
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, Me.Text)
End Try
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conexion()
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Private Sub BtnBuscar_Click(sender As Object, e As EventArgs) Handles BtnBuscar.Click
Dim arrimage() As Byte
Dim conn As New OleDb.OleDbConnection
Dim Myconnection As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\BD de imagenes\BD de imagenes\DBImagenes.mdb"
conn.ConnectionString = Myconnection
conn.Open()
sql = "Select * from TBImg where Nombre=" & (TBBuscar.Text)
Dim cmd As New OleDbCommand
With cmd
.Connection = conex
.CommandText = sql
End With
Dim publictable As New DataTable
Try
da.SelectCommand = cmd
da.Fill(publictable)
TextBox1.Text = publictable.Rows(1).Item("Nombre").ToString
arrimage = publictable.Rows(1).Item("Imagen")
Dim mstream As New System.IO.MemoryStream(arrimage)
PictureBox1.Image = Image.FromStream(mstream)
Catch ex As Exception
MsgBox(ex.Message)
Finally
da.Dispose()
conn.Close()
End Try
End Sub
End Class
the relevant part is at Private Sub BtnBuscar_Click.
I'm trying to search in a textbox for the name that I saved the image with. but I haven't had success all I get is the error of the title.
this is how my database looks like the images are saved as an ole object
This is the error I get
I was following this tutorial https://www.youtube.com/watch?v=zFdjp39mfhQ
but he didn't quite explain how to use the:
TextBox1.Text = publictable.Rows(0).Item(1)
arrimage = publictable.Rows(0).Item(1)'
don't know if it's the cause of the issue.
instructions. The reason why my code looks different is that I was trying to stuff to see if I could make it work.
I have tried to search for answers and people suggest that I may have put the table name wrong or the column but I copied the name exactly how it is in the table with ctrl + c and ctrl + v.
what I want is that when I type the name in the column name of the database that it brings the designated picture stored as ole object onto my desired picture box on my form app.
Needless to say, I'm not that experienced with vb.net and SQL, Acces. I'm just following tutorials for being able to complete the project.
Do not declare connections or commands or datareaders at the class level. They all need to have their Dispose methods called. Using blocks will have the declare, closing and disposing even if there is an error. Streams also need Using blocks.
Defaults for an OpenFiledialog
Multiselect is False
CheckFileExists is True
CheckPathExists is True
DereferenceLinks is True
ValidateNames is True
FileName is ""
Unless you are getting paid by the line, it is unnecessary to reset these values to their defaults.
I have alerted your Filter to exclude All Files. You also had jpg appearing twice.
I declared a variable to hold the file extension, PictureFormat, of the image file so you could provide the proper parameter for ImageFormat.
When you retrieve the image field from the database it comes as an Object. To get the Byte() a DirectCast should work.
Private PictureFormat As String
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
FillPictureBoxFromFile()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles BTNGuardar.Click
Try
saveimage()
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
MsgBox("Image has been saved in the database")
End Sub
Private cnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\BD de imagenes\BD de imagenes\DBImagenes.mdb"
Private Sub saveimage()
Dim arrimage() As Byte
Using mstream As New System.IO.MemoryStream
If PictureFormat.ToLower = ".png" Then
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Png)
ElseIf PictureFormat.ToLower = ".jpg" Then
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
arrimage = mstream.GetBuffer()
Dim Filesize As Long
Filesize = mstream.Length
End Using
Using con As New OleDbConnection(cnStr),
cmd As New OleDbCommand("Insert into TBImg (Imagen, Nombre) Values (#Imagen, #Nombre)", con)
With cmd
.Parameters.Add("#Imagen", OleDbType.Binary).Value = arrimage
.Parameters.Add("#Nombre", OleDbType.VarChar).Value = TextBox1.Text
con.Open()
.ExecuteNonQuery()
End With
End Using
End Sub
Private Sub BtnExaminar_Click(sender As Object, e As EventArgs) Handles BtnExaminar.Click
FillPictureBoxFromFile()
End Sub
Private Sub BtnBuscar_Click(sender As Object, e As EventArgs) Handles BtnBuscar.Click
Dim dt As DataTable
Try
dt = GetDataByName(TBBuscar.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
TextBox1.Text = dt(0)("Nombre").ToString
Dim arrimage = DirectCast(dt(0)("Imagen"), Byte())
Dim mstream As New System.IO.MemoryStream(arrimage)
PictureBox1.Image = Image.FromStream(mstream)
End Sub
Private Function GetDataByName(name As String) As DataTable
Dim dt As New DataTable
Using conn As New OleDb.OleDbConnection(cnStr),
cmd As New OleDbCommand("Select * from TBImg where Nombre= #Buscar", conn)
cmd.Parameters.Add("#Buscar", OleDbType.VarChar).Value = TBBuscar.Text
conn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub FillPictureBoxFromFile()
With OpenFileDialog1
.Filter = "(*.jpg)|*.jpg|(*.png)|*.png"
.RestoreDirectory = True
.Title = "Select a file to open"
If .ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
PictureFormat = Path.GetExtension(OpenFileDialog1.FileName)
End With
End Sub

Displaying and review pdf files in Adobe reader tool

I use code to view pdf files in adobe reader tool then store them in sql server database,
What I want is a way to display these stored files when I double click on the file name in datagridview
I use this code to display pdf files:
Private Sub btnNewItem_Click(sender As Object, e As EventArgs) Handles btnNewItem.Click
txtItemNO.Text = GetmaxID()
btnSaveItem.Enabled = True
ofd.Filter = "pdf Files|*.pdf"
If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
txtpdfPath.Text = ofd.FileName
AxAcroPDF1.src = txtpdfPath.Text
End If
End Sub
and this code to save them in database:
Private Sub btnSaveItem_Click(sender As Object, e As EventArgs) Handles btnSaveItem.Click
Try
cmd = New SqlCommand("insert into TBL_Attaches (AttachID, AttachName, AttachDate, Picture, CatID) values (#AttachID, #AttachName, #AttachDate, #Picture, #CatID)", con)
con.Open()
With cmd.Parameters
.AddWithValue("#AttachID", txtItemNO.Text)
.AddWithValue("#AttachName", txtItemName.Text)
.AddWithValue("#AttachDate", dtDateSave.Value)
Dim fs As New FileStream(ofd.FileName, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fs)
Dim Filepdf() As Byte = br.ReadBytes(br.BaseStream.Length)
.AddWithValue("#Picture", Filepdf)
.AddWithValue("#CatID", cmbItemCat.SelectedValue)
End With
cmd.ExecuteNonQuery()
MsgBox("Done!", MsgBoxStyle.Information, "Save")
dgsittings()
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
and this is the code I used to show files name in datagridview:
adapter = New SqlDataAdapter("select TBL_Attaches.AttachID, TBL_Attaches.AttachName, TBL_Attaches.AttachDate, TBL_CatFailes.CatName from TBL_Attaches inner join TBL_CatFailes on TBL_Attaches.CatID = TBL_CatFailes.CatID", con)
Dim dtG As New DataTable
adapter.Fill(dtG)
dgAttached.DataSource = dtG
I just want to display pdf file when I double click on it's name in the datagridview

VB.NET How to Update DataSource from DataGridView (Binding to Dataset.DataTable)

Halo All..
I'm working with Visual Studio 2019 to create WinFormApp
What i'm working with as follow:
Adding New DataSource from wizard which connect to Acces Database (store locally within app), Acces Database name is Supplier with only Headers (9 Headers) and no data.
Adding DataGridView to Form and bind it to SupplierDataSet.SupplierDataTable
Adding OpenFileDialog where users can browse Excel File then select Sheet Name and view the data in DataGridView.
Adding Import Button to save/update SupplierDataSet.SupplierDataTable
Here is my code:
Imports System.IO
Imports ExcelDataReader
Public Class Form2
Dim tables As DataTableCollection
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub BtnBrowse_Click(sender As Object, e As EventArgs) Handles BtnBrowse.Click
'read excel file
Using ofd As OpenFileDialog = New OpenFileDialog() With
{.Filter = "Excel Workbook|*.xlsx"}
If ofd.ShowDialog() = DialogResult.OK Then
TxtFileName.Text = ofd.FileName
Using stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read)
Using reader As IExcelDataReader = ExcelReaderFactory.CreateReader(stream)
Dim result As DataSet = reader.AsDataSet(New ExcelDataSetConfiguration() With {
.ConfigureDataTable = Function(__) New ExcelDataTableConfiguration() With {
.UseHeaderRow = True}})
tables = result.Tables
CboSheet.Items.Clear()
For Each table As DataTable In tables
CboSheet.Items.Add(table.TableName)
Next
End Using
End Using
End If
End Using
End Sub
Private Sub CboSheet_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CboSheet.SelectedIndexChanged
'Pupulate excel file data to DataGridView
Dim dt As DataTable = tables(CboSheet.SelectedItem.ToString())
DataGridView1.DataSource = dt
End Sub
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
'Here the code which I want to save/update SupplierDataSet.SupplierDataTable.
End Sub
End Class
Since i'm new for this (approx 2 weeks). I've no clue to how to update the DataTable
Please Help Me. Any help will be appreciated.
And So Many Thanks Before.

Easy and fast load datagrid from textfile with 100k rows using vb.net

I have a created a program with VB.net, where text file is used to load datagrid, but its very slow, there is a lot of code, when there are many line imports from text file.
Is there any simpler way to code this, so datagrid loading isn't so slow?
Private Sub Load_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Load.Click
OpenFileDialog1.Filter = "Text Files|*.txt|All Files|*.*"
OpenFileDialog1.Title = "Select Text File for Path"
OpenFileDialog1.FileName = "Select File"
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.Ok Then
txttblnm.Text = OpenFileDialog1.FileName
txtfilenm.Text = System.IO.Path.GetFileName(txttblnm.Text)
txtfilenm.Text = txtfilenm.Text.Substring(0, txtfilenm.Text.Length - 4)
Label7.Text = System.IO.Path.GetDirectoryName(txttblnm.Text)
End If
If Len(txtfilenm.Text) = 8 And CheckBox1.CheckState = CheckState.Checked Then
Dim textfiles() = Directory.GetFiles(Label7.Text, "*.txt")
For Each file As String In textfiles
Call dgv1_load()
Call Access_export()
Call clear_item()
Next
ElseIf Len(txtfilenm.Text) >= 9 Then
MsgBox("Please Load DATA", MsgBoxStyle.Information, "Load Data Error")
Exit Sub
End If
End Sub
You're interacting far too much with the user interface. Every interaction with the gridview + textboxes is expensive.
What you should do is start by creating a DataTable and fill this with the row data.
Then after it's all loaded set the datagridview.DataSource to this table and everything will be drawn only once.
Private Function ParseFile(filename As String) As DataTable
Dim result As New DataTable()
result.Columns.Add("colname 1 ....")
result.Columns.Add("colname 2 ....")
Using inputFile As New StreamReader(filename) 'Open text file
Do Until inputFile.EndOfStream
Dim row = result.Rows.Add()
row(0) = "blah"
Loop
End Using
return result
End Function
Private Sub ShowResult()
dgv1.DataSource = ParseFile(filename)
End Sub

Im cant get a doc from my documents to display

Imports System.IO
Public Class Form1
Private Sub MenuItem1_Click(sender As Object, e As EventArgs) Handles MenuItem1.Click
Me.txtFileContent.Text = Nothing
End Sub
Private Sub MenuItem2_Click(sender As Object, e As EventArgs) Handles MenuItem2.Click
Me.txtFileContent.Text = Nothing
End Sub
Private Sub MenuItem3_Click(sender As Object, e As EventArgs) Handles MenuItem3.Click
Me.savSaveFile.ShowDialog()
Dim strFileName As String = Me.savSaveFile.FileName
Dim fs As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Dim TextFile As New StreamWriter(fs)
TextFile.Write(Me.txtFileContent.Text)
TextFile.Close()
fs.Close()
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MenuItem5.Click
Me.savSaveFile.ShowDialog()
Dim strFileName As String = Me.savSaveFile.FileName
Dim fs As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
Dim TextFile As New StreamWriter(fs)
TextFile.Close()
fs.Close()
End Sub
End Class
What im trying to do is display a "open" document dialog box so the text inside the box can be displayed into the text box. I did the same with the "save" document dialog box and it worked fine just confused on the Open part. Thanks a million everyone.
There are two different kind of dialog box for selecting files.
One for save operations and one for opening files.
Your code seems to use the same one and from the name I think it is a SaveFileDialog.
To open a file you need a OpenFileDialog and use a StreamReader not a StreamWriter
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MenuItem5.Click
' Create an OpenFileDialog here, for more precise property settings see the link above'
Dim openDlg = New OpenFileDialog()
' If user presses OK'
if openDlg.ShowDialog() = DialogResult.OK Then
' Still the filename selected could be empty, need to check'
Dim strFileName As String = openDlg.FileName
if strFileName.Trim().Length > 0 then
' Open the file using a reader, not a writer'
Using fs = New FileStream(strFileName, FileMode.Open, FileAccess.Read)
Using TextFile = New StreamReader(fs)
' Read everything (caution this should be used only for small files)'
Dim fileContent = TextFile.ReadToEnd
' Pass everything into a TextBox control for display'
Me.txtFileContent.Text = fileContent
End Using
End Using
End If
End If
End Sub