empty path name is not legal (vb.net 2005 ,access 2000,) - vb.net

[Error] empty path name is not legal
The problem is I cannot insert image to Access database. Which line is error. Thanks In advance who helping me
Regards,
Fizul
Dim OpenFileDialog1 As New OpenFileDialog
Dim fsreader As New IO.FileStream(OpenFileDialog1.FileName,IO.FileMode.Open, IO.FileAccess.Read)
Dim breader As New IO.BinaryReader(fsreader)
Dim imgbuffer(fsreader.Length) As Byte
breader.Read(imgbuffer, 0, fsreader.Length)
fsreader.Close()
cnn.ConnectionString = "provider=microsoft.ace.oledb.12.0; data source = |datadirectory|\db1.accdb;"
cnn.Open()
Dim sql As String
sql = "insert into Table1 Values(" & TextBox1.Text & ",'" & imgbuffer.Length & "')"
Dim cmd As New OleDb.OleDbCommand(sql, cnn)
cmd.ExecuteNonQuery()
cmd.Dispose()
cnn.Close()

The problem is in these first two lines:
Dim OpenFileDialog1 As New OpenFileDialog
Dim fsreader As New IO.FileStream(OpenFileDialog1.FileName,IO.FileMode.Open, IO.FileAccess.Read)
You created an instance of OpenFileDialog, but you never called it's ShowDialog method so the FileName property is Nothing. You need something like this:
Using OpenFileDialog1 As New OpenFileDialog
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Dim fsreader As New IO.FileStream(OpenFileDialog1.FileName,IO.FileMode.Open, IO.FileAccess.Read)
'remaining of code here
End If
End Using
The Using statement makes sure that the dialog is disposed correctly.

Related

Set datasource of datagridview in module

I am writing a program that will automatically process files, based on a set of criteria. In order to process these, I need to load the Excel file first, before I can process it.
I create a module called "NewBusAuto". In here, I created a new datagridview. I am trying to set the datasource of this, but whenever I do, it doesn't actually bind. When I try and process each row/column, it is saying it is still empty.
Code used:
Module m_NewBusinessAutomation
Dim dgvImport As DataGridView
Public Sub NewBusAuto(ByVal folderName As String,
ByVal fileName As String,
ByVal executeScript As String)
dgvImport = New DataGridView
If Path.GetExtension(fileName) = ".xls" Or Path.GetExtension(fileName) = ".xlsx" Then
Using cn As New System.Data.OleDb.OleDbConnection
Dim builder As New OleDbConnectionStringBuilder With _
{.DataSource = folderName & "\" & fileName,
.Provider = "Microsoft.ACE.OLEDB.12.0"}
builder.Add("Extended Properties", "Excel 12.0; IMEX=1;HDR=Yes;")
cn.ConnectionString = builder.ConnectionString
cn.Open()
Using cmd As OleDbCommand = New OleDbCommand With {.Connection = cn}
cmd.CommandText = "SELECT * FROM [Sheet1$]"
Dim dr As System.Data.IDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
dgvImport.DataSource = dt
dgvImport.Refresh()
Messagebox.show(dgvImport.RowCount & "-" & dgvImport.ColumnCount)
dr.Close()
End Using
End Using
End If
The messagebox is giving me "0 - 0" as a result.
I need to load the Excel file to the actual database. Any help would be appreciated!

cant find Isam installable CSV Files

Hey I am having a problem taking an excel spread sheet and inserting it into a data-grid in Visual Studio 2013 I was wondering if anyone could give me a hand.
Here is the code I have at the moment.
getting the error Could not find installable ISAM only when I have clicked on the csv fle iut works for ll the other files?
OpenFileDialog1.ShowDialog()
Dim filePath As String = OpenFileDialog1.FileName
Dim extension As String = Path.GetExtension(filePath)
Dim header As String = If(rbHeaderYes.Checked, "YES", "NO")
Dim conStr As String, sheetName As String
conStr = String.Empty
Select Case extension
Case ".xls"
'Excel 97-03
conStr = String.Format(Excel03ConString, filePath, header)
Exit Select
Case ".xlsx"
'Excel 07
conStr = String.Format(Excel07ConString, filePath, header)
Exit Select
Case ".csv"
'CSV
conStr = String.Format(ExcelCsv, filePath, header)
Exit Select
End Select
'Get the name of the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
cmd.Connection = con
con.Open()
Dim dtExcelSchema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
sheetName = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()
con.Close()
End Using
End Using
'Read Data from the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
Using oda As New OleDbDataAdapter()
Dim dt As New DataTable()
cmd.CommandText = (Convert.ToString("SELECT * From [") & sheetName) + "]"
cmd.Connection = con
con.Open()
oda.SelectCommand = cmd
oda.Fill(dt)
con.Close()
'Populate DataGridView.
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub

How to export data from Access to a text file

net. My question is how to export data from Access to a text file using vb.net. In my database has Table1 which consists FirstName and LastName so I want this data to be exported to a text file.
I stumble on this code and run it and when compiled it but nothing is export to the text file. Can Someone help my with this?
Dim connetionString As String
Dim cnn As OleDbConnection
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Scripts\db.mdb;"
cnn = New OleDbConnection(connetionString)
cnn.Open()
Dim AccessCommand As New System.Data.OleDb.OleDbCommand("SELECT * INTO [Text;HDR=No;DATABASE=C:\Scripts\TextFiles].[Result.txt] FROM Table1", cnn)
cnn.Close()
Thanks in advance!
This question is downvoted is because you can actually find plenty of example from the website.
Perhaps you do not know what keyword to search?
Try something like "dataset to textbox"?
or something here? Export a C# DataSet to a text file
Updated
I understand you may be new to vb. I will not give you the exact code but tell you what you can do.
First, declare a dataTable/dataset (I would prefer DataTable) to hold your query result from DB.
Dim dtresult As DataTable = 'Result from DB
Then loop through the datatable rows and get the data append into a string builder(or any other way you like to build your string)
Then append the string into the txt file.
This is something you can do.
UPDATE 2
Okay, something like this.
Private Sub DataTableToTXT()
Dim connetionString As String
Dim cnn As OleDbConnection
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Scripts\db.mdb;"
cnn = New OleDbConnection(connetionString)
Dim dtResult As New DataTable
cnn.Open()
'Change the query
Dim dataAdap As New OleDbDataAdapter("SELECT * FROM TABLE1", cnn)
dataAdap.Fill(dtResult)
cnn.Close()
'Change the path to your desired path
Dim exportPath As String = "C:\Export\"
Dim exportFileName As String = "data.txt"
If Not Directory.Exists(exportPath) Then
Directory.CreateDirectory(exportPath)
End If
Dim writer As New StreamWriter(exportPath + exportFileName)
Try
Dim sb As New StringBuilder
For Each row As DataRow In dtResult.Rows
sb = New StringBuilder
For Each col As DataColumn In dtResult.Columns
sb.Append(row(col.ColumnName))
Next
writer.WriteLine(sb.ToString())
Next
Catch ex As Exception
Throw ex
Finally
If Not writer Is Nothing Then writer.Close()
End Try
End Sub

Excel to SQL Table with VB.net

I've read all the articles and posts from other users on this subject and I'm still stuck.
Essentially what I have is a VB.net program with a local SQL backend. I created a table called "consolDump" that I wish to import an Excel sheet into. I feel like I'm very close just from the help I've gotten from the other people with a similar problem. Just to clarify, I do not have the ability to add software to the machine I'm using (it's heavily restricted by IT), and do not have access to the SQL server import utility.
Here's the code I have. Any help would be appreciated.
Imports System.Data.SqlClient
Public Class formImport
Private Sub buttonConsolImport_Click(sender As Object, e As EventArgs) Handles buttonConsolImport.Click
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim fBrowse As New OpenFileDialog
Dim fname As String
Try
With fBrowse
.Filter = "Excel files(*.xls)|*.xls|All files (*.*)|*.*"
.FilterIndex = 1
.Title = "Import data from Excel file"
End With
If fBrowse.ShowDialog() = Windows.Forms.DialogResult.OK Then
fname = fBrowse.FileName
MyConnection = New System.Data.OleDb.OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fname & ";" & "Extended Properties=""Excel 8.0;HDR=NO;IMEX=1""")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("A1, B1, C1, D1, E1, F1, G1, H1, I1, J1, k1, L1 from [consol_data$]", MyConnection)
MyCommand.TableMappings.Add("Table", "consolDump")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
For Each Drr As DataRow In DtSet.Tables(0).Rows
Execute_Local("INSERT INTO consolDump(PO_Number, Consol_ID, Status, Contractor, UTAS_Owner, Description, Start_Date, End_Date, Total_Spend, ) VALUES ('" & Drr(0).ToString & "','" & Drr(1).ToString & "','" & Drr(2).ToString & "'),'" & Drr(3).ToString & "','" & Drr(4).ToString & "','" & Drr(5).ToString & "','" & Drr(6).ToString & "','" & Drr(7).ToString & "','" & Drr(8).ToString & "','" & Drr(9).ToString & "','" & Drr(10).ToString & "','" & Drr(11).ToString & "'")
Next
MsgBox("Success")
MyConnection.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
Ok so, to add to what I've asked, I'm trying to import a csv file from the excel sheet with this code, which works fine.
'Converts consol data to csv file===========================
Dim excelApplication As New Excel.Application
Dim excelWrkBook As Excel.Workbook
excelApplication.Visible = False
excelApplication.DisplayAlerts = False
excelWrkBook = excelApplication.Workbooks.Open("R:\PECOE-WLOX\QuEST\Torres\sqlProjects\consol_data.xls")
excelWrkBook.SaveAs(Filename:="R:\PECOE-WLOX\QuEST\Torres\sqlProjects\consol_data.csv", FileFormat:=Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)
excelWrkBook.Close()
excelApplication.DisplayAlerts = True
excelApplication.Quit()
MessageBox.Show("Converted to CSV")
'============================================================
Now I'm trying to import the csv file into a new data table but I'm getting a strange error that says "system.data.sql is a namespace and cannot be used as an expression". Now this is probably my inexperience as I pulled the code from another site and several said they have it working. I've modified it to fit my data. Any help would be appreciated. The error appears as a syntax error on "Dim cmd As New SqlClient.SqlCommand(Sql, connection)". It's highlighting the Sql in the paranthesis as a namespace.
Dim consolDump1 As New DataTable()
consolDump1.Columns.Add("PO_Number")
consolDump1.Columns.Add("Consol_ID")
consolDump1.Columns.Add("Status")
consolDump1.Columns.Add("Contractor")
consolDump1.Columns.Add("UTAS_Owner")
consolDump1.Columns.Add("Description")
consolDump1.Columns.Add("Start_Date")
consolDump1.Columns.Add("End_Date")
consolDump1.Columns.Add("Total_Spend")
consolDump1.Columns.Add("Job_Title")
consolDump1.Columns.Add("Location")
consolDump1.Columns.Add("Type")
Dim parser As New FileIO.TextFieldParser("R:\PECOE-WLOX\QuEST\Torres\sqlProjects\consol_data.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True ' each of the values is enclosed with double quotes
parser.TrimWhiteSpace = True
parser.ReadLine()
Do Until parser.EndOfData = True
consolDump1.Rows.Add(parser.ReadFields())
Loop
Dim strSql As String = "INSERT INTO consolDump(PO_Number,Consol_ID,Status,Contractor,UTAS_Owner,Description,Start_Date,End_Date,Total_Spend,Job_Title,Location,Type) VALUES (#PO_Number,#Consol_ID,#Status,#Contractor,#UTAS_Owner,#Description,#Start_Date,#End_Date,#Total_Spend,#Job_Title,#Location,#Type)"
Dim SqlconnectionString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\consolData.mdf;Integrated Security=True;Connect Timeout=30"
Using connection As New SqlClient.SqlConnection(SqlconnectionString)
Dim cmd As New SqlClient.SqlCommand(Sql, connection)
' create command objects and add parameters
With cmd.Parameters
.Add("#PO_Number", SqlDbType.VarChar, 15, "PO_Number")
.Add("#Consol_ID", SqlDbType.BigInt, "Consol_ID")
.Add("#Status", SqlDbType.Text, "Status")
.Add("#Contractor", SqlDbType.Text, "Contractor")
.Add("#UTAS_Owner", SqlDbType.Text, "UTAS_Owner")
.Add("#Description", SqlDbType.Text, "Description")
.Add("#Start_Date", SqlDbType.Date, "Start_Date")
.Add("#End_Date", SqlDbType.Date, "End_Date")
.Add("#Total_Spend", SqlDbType.Money, "Total_Spend")
.Add("#Job_Title", SqlDbType.Text, "Job_Title")
.Add("#Location", SqlDbType.Text, "Location")
.Add("#Type", SqlDbType.Text, "Type")
End With
Dim adapter As New SqlClient.SqlDataAdapter()
adapter.InsertCommand = cmd
'--Update the original SQL table from the datatable
Dim iRowsInserted As Int32 = adapter.Update(consolDump1)
End Using
End Sub
There is an extra comma at the end of the column list in your sql query:
End_Date, Total_Spend, )
You need this:
End_Date, Total_Spend )
Also, the column list has 9 items, but your values list has 12. Are you maybe missing a few columns?
Finally for this section, it doesn't matter much with code for personal use, but what you're doing with string concatenation to put the excel data into your query is considered bad practice. If you do that in product code, you're creating a huge security hole. Instead, learn about parameterized queries.
In the later sample, you define your sql string this way:
Dim strSql As String
But try to include in your command this way:
Dim cmd As New SqlClient.SqlCommand(Sql, ...
You should do this:
Dim cmd As New SqlClient.SqlCommand(strSql, ...
Also, based on the other code, if this is an access database, you should still be using the OleDbCommand and OleDbConnection objects, in the System.Data.OleDb namespace.
What I would do is somewhere in between your first sample and your second:
Imports System.Data.SqlClient
Private Sub buttonConsolImport_Click(sender As Object, e As EventArgs) Handles buttonConsolImport.Click
Dim fBrowse As New OpenFileDialog
With fBrowse
.Filter = "Excel files(*.xls)|*.xls|All files (*.*)|*.*"
.FilterIndex = 1
.Title = "Import data from Excel file"
End With
If fBrowse.ShowDialog() <> Windows.Forms.DialogResult.OK Then Exit Sub
Dim fname As String = fBrowse.FileName
Dim sql As String = "INSERT INTO consolDump(PO_Number,Consol_ID,[Status],Contractor,UTAS_Owner,Description,Start_Date,End_Date,Total_Spend,Job_Title,Location,Type) VALUES (#PO_Number,#Consol_ID,#Status,#Contractor,#UTAS_Owner,#Description,#Start_Date,#End_Date,#Total_Spend,#Job_Title,#Location,#Type)"
Try
Dim parser As New FileIO.TextFieldParser(fname)
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True ' each of the values is enclosed with double quotes
parser.TrimWhiteSpace = True
parser.ReadLine() 'skip column headers
Using cn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\consolData.mdf;Integrated Security=True"),
cmd As New SqlCommand(sql, cn)
With cmd.Parameters
.Add("#PO_Number", SqlDbType.VarChar, 15)
.Add("#Consol_ID", SqlDbType.BigInt)
.Add("#Status", SqlDbType.Text) 'I doubt that "Text" is the right type for all of these
.Add("#Contractor", SqlDbType.Text) 'If it is, you may want to examine your table schema
.Add("#UTAS_Owner", SqlDbType.Text)
.Add("#Description", SqlDbType.Text)
.Add("#Start_Date", SqlDbType.Date)
.Add("#End_Date", SqlDbType.Date)
.Add("#Total_Spend", SqlDbType.Money)
.Add("#Job_Title", SqlDbType.Text)
.Add("#Location", SqlDbType.Text)
.Add("#Type", SqlDbType.Text)
End With
cn.Open()
Do Until parser.EndOfData = True
Dim fields() As String = parser.ReadFields()
For i As Integer = 0 To 11
cmd.Parameters(i).Value = fields(i)
Next
cmd.ExecuteNonQuery()
Loop
End Using
MsgBox("Success")
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

Updating Image file in database using MS Access

Here is my code
Dim Cmd As New OleDbCommand
Dim strsql As String
Try
Dim fsreader As New FileStream(OpenFile.FileName, FileMode.Open, FileAccess.Read)
Dim breader As New BinaryReader(fsreader)
Dim imgbuffer(fsreader.Length) As Byte
breader.Read(imgbuffer, 0, fsreader.Length)
fsreader.Close()
strsql = "UPDATE AccResult SET (PicFile, PicName) Values (#pfile, #pname) WHERE StudNo = '" & Form1.sNo.Text & "'"
Cmd = New OleDbCommand(strsql, con)
Cmd.Parameters.AddWithValue("#pfile", txtSave.Text)
Cmd.Parameters.AddWithValue("#pname", imgbuffer)
Cmd.ExecuteNonQuery()
Cmd.Dispose()
Catch ex As Exception
End Try
please help me how can i update the students data when saving their picture in database. im using VB.NET. Thank You.
Looks like simple error in your logic - you have the filename reversed with the file content
Cmd.Parameters.AddWithValue("#pfile", txtSave.Text)
Cmd.Parameters.AddWithValue("#pname", imgbuffer)
Should be
Cmd.Parameters.AddWithValue("#pfile", imgbuffer)
Cmd.Parameters.AddWithValue("#pname", txtSave.Text)