vb.net if database not found open a OpenFileDialog - vb.net

I use following code to set a connection to my database: Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FileRename v5.4.accdb")
I wanted to extent this function by checking if the database exists and If NOT to open a FileOpenDialog to choose another database in another folder. I cant seem to get it to work because when I place the FileOpenDialog on my Main form it throws an Exception error.
Public Function Jokendb() As OleDbConnection
Dim FileName As String = Application.StartupPath & "\FileRename v5.4.accdb"
If IO.File.Exists(FileName) Then
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FileRename v5.4.accdb")
Else
'Dim result As DialogResult = OpenFileDialog1.ShowDialog()
Dim str As String = OpenFileDialog1.FileName.ToString()
'If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
' Get the file name.
Dim path As String = OpenFileDialog1.FileName
Try
' Read in text.
Dim text As String = File.ReadAllText(path)
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & text)
Catch ex As Exception
' Report an error.
Me.Text = "Error"
End Try
'End If
End If
End Function

I don't know why those line are comented but i think your code could work with these changes:
Public Function Jokendb() As OleDbConnection
Dim FileName As String = Application.StartupPath & "\FileRename v5.4.accdb"
If IO.File.Exists(FileName) Then
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FileRename v5.4.accdb")
Else
OpenFileDialog1.ShowDialog()
'Dim str As String = OpenFileDialog1.FileName.ToString()
'If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
' Get the file name.
Dim path As String = ""
If OpenFileDialog1.filename <> "" Then
path = OpenFileDialog1.FileName
End If
Try
' Read in text.
Dim text As String = File.ReadAllText(path)
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & text)
Catch ex As Exception
' Report an error.
Me.Text = "Error"
End Try
'End If
End If
End Function

Related

having problem with reading docx and pptx files from access attachmant field

I have a program that stores files in a attachment field in access database.
Here's the code I use to insert files:
Imports Microsoft.Office.Interop.Access.Dao
Private Sub insert_file(ByVal path As String)
Dim dbe As New DBEngine
Dim db As Database = dbe.OpenDatabase(My.Application.Info.DirectoryPath &"\Mydatabase.accdb")
Dim rstrecord As Recordset = db.OpenRecordset("select * from tblfiles where id=1", RecordsetTypeEnum.dbOpenDynaset)
rstrecord.Edit()
Dim rstattachments As Recordset2 = rstrecord.Fields("File").Value
rstattachments.AddNew()
Dim attachmentdata As Field2 = rstattachments.Fields("FileData")
attachmentdata.LoadFromFile(path)
rstattachments.Update()
rstattachments.Close()
rstrecord.Update()
rstrecord.Close()
db.Close()
End Sub
and I have a option to export the files.Here is the code:
Private Sub export(ByVal id As Integer, ByVal filestr As String, path As String)
DS.Reset()
con = New OleDbConnection(strcon)
con.Open()
cmdtxt = "SELECT ID, File.FileName,File.FileType, File.FileData FROM tblfiles where ID=" & id & " and File.FileName = '" & filestr & "' "
DA = New OleDbDataAdapter(cmdtxt, con)
DA.Fill(DS, "tblfiles")
con.Close()
Dim savestr As String = path
Dim byt() As Byte = DS.Tables("tblfiles").Rows(0).Item("File.FileData")
Try
File.WriteAllBytes(savestr, byt)
MessageBox.Show(File exported successfully)
Catch ex As Exception
messagebox.show(ex.message)
End Try
End Sub
There is no error in inserting and exporting files but when I export pptx and docx files and I open them I receive the following messages:
docx:The file is corrupt and can not be open.
pptx:powerpoint found a problem with content in file.powerpoint can attempt to repair the presentation.

Check if value exist in DBF database

I am trying to check if value "IAV-1419" exist in second column (ColName) in database named PROMGL.DBF.
I get this error : No value give for one or more required parameters
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "[NALOG,C,8]"
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV"
cmd = New OleDbCommand("SELECT * FROM PROMGL WHERE [NALOG,C,8] = #NAL")
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#NAL", "IAV-1419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
con.Close()
Label6.Text = "EXIST"
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
End Using
I am stuck here, if anyone could please check this code for me.
are you sure that your connectionstring is correct????
Data Source=" & FilePath &
how connection string know the database where it point only to "C:\" i think is missing database name
Another personal suggestion make your code more simple to read in example :
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "[NALOG,C,8]"
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT * FROM PROMGL WHERE [NALOG,C,8] = #NAL", con
cmd.Parameters.AddWithValue("#NAL", "IAV-1419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
Label6.Text = "EXIST"
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
End Using
End Using
End Using

Avoid duplicate coding in vb.net

I'm working on some project which involves many forms .. in each form i have to import an excel into datagrid using below code .. i dont want to duplicate the code for each form .. planning to create module so that i can call the function from each form to import the excel data into datagrid .
Try
With Form1.OpenFileDialog1
.Title = "Please open the STM_Ticket_Template"
.Filter = "Excel Files | *.xlsx"
If .ShowDialog = Windows.Forms.DialogResult.OK Then
Dim fn1 As String = .FileName.ToString
Dim oledbCon As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + fn1 + ";Extended Properties=Excel 12.0;"
conDB = New OleDb.OleDbConnection(oledbCon)
adap = New OleDb.OleDbDataAdapter("Select * From [SAM_TICKETS$]", conDB)
adap.TableMappings.Add("Table", "Excel")
dSet = New DataSet
adap.Fill(dSet)
Me.DataGridView1.DataSource = dSet.Tables(0)
End If
End With
Dim msg As String = MsgBox("Template successfully loaded", MsgBoxStyle.Information, "Creation Template")
Catch ex As Exception
MsgBox("Load Error..." + Environment.NewLine + ex.ToString)
End Try
is there any way to do this ?.
any suggestion appreciated :)
You may have a function:
Imports System.Windows.Forms
Public Function GetExcelTable() AS DataTable
Dim od As OpenFileDialog = new OpenFileDialog
od.ShowDialog
try
With od
.Title = "Please open the STM_Ticket_Template"
.Filter = "Excel Files | *.xlsx"
If .ShowDialog = Windows.Forms.DialogResult.OK Then
Dim fn1 As String = .FileName.ToString
Dim oledbCon As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + fn1 + ";Extended Properties=Excel 12.0;"
conDB = New OleDb.OleDbConnection(oledbCon)
adap = New OleDb.OleDbDataAdapter("Select * From [SAM_TICKETS$]", conDB)
adap.TableMappings.Add("Table", "Excel")
dSet = New DataSet
adap.Fill(dSet)
Return dSet.Tables(0)
End If
End With
Dim msg As String = MsgBox("Template successfully loaded", MsgBoxStyle.Information, "Creation Template")
Catch ex As Exception
MsgBox("Load Error..." + Environment.NewLine + ex.ToString)
End Try
End Function
and then call it as:
Me.DataGridView1.DataSource = GetExcelTable()
It looks like a pattern you can put into a sub or function and make that call each time you need to call an import:
Public Sub ImportForm()
'Import Logic
End Sub
Then call ImportForm() everywhere you need it.
Here is a tutorial on Standard Modules in VB .NET.
This will allow you to create your Excel logic in one place and have it be called from multiple forms.
I would create a function like yparask does, but then pass the datagrid
Public Function GetExcelTable(Dgv as datagridview) AS boolean
' do your openfile and import stuff here
return true ' succesfull
return false ' unsuccesfull

Prevent Excel pop up message in VB code

I am having a problem with the "File Now Available" message box popping open from excel when i importing a file to my program.
http://oi50.tinypic.com/23wajt.jpg
Private Function XLSSelect_Click(strFileName As String) As DataTable
Dim connectionStringTemplate As String = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};" + "Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"""
Dim connectionString As String = String.Format(connectionStringTemplate, strFileName)
Try
Dim sqlSelect As String = "SELECT * FROM [" & GetExcelSheetNames(strFileName)(0) & "];"
' Load the Excel worksheet into a DataTable
Dim workbook As DataSet = New DataSet()
Dim excelAdapter As System.Data.Common.DataAdapter = New System.Data.OleDb.OleDbDataAdapter(sqlSelect, connectionString)
excelAdapter.Fill(workbook)
For i As Integer = 0 To workbook.Tables(0).Columns.Count - 1
workbook.Tables(0).Columns(i).ColumnName = workbook.Tables(0).Columns(i).ColumnName.ToString.Trim.Replace(" ", "")
Next
Return workbook.Tables(0).Copy
Catch
Throw New Exception("Error reading from Excel Spreadsheet. Are you sure this file isn't currently open in Excel, and that it has been saved as a .xls through Excel at least once?")
End Try
Return Nothing
End Function
Private Shared Function GetExcelSheetNames(excelFile As String) As [String]()
Dim objConn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Try
Dim connString As [String] = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & excelFile & ";Extended Properties=Excel 12.0;"
' Create connection object by using the preceding connection string.
objConn = New OleDbConnection(connString)
' Open connection with the database.
objConn.Open()
' Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheets As [String]() = New [String](dt.Rows.Count - 1) {}
Dim i As Integer = 0
'Add the sheet name to the string array.
For Each row As DataRow In dt.Rows
excelSheets(i) = row("TABLE_NAME").ToString()
i += 1
Next
Return excelSheets
Catch ex As Exception
Return Nothing
Finally
' Clean up.
If objConn IsNot Nothing Then
objConn.Close()
objConn.Dispose()
End If
If dt IsNot Nothing Then
dt.Dispose()
End If
End Try
End Function
Anyone know how i can go about disabling this ?
Dim appExcel As Excel.Application
Set appExcel = New Excel.Application
appExcel.Workbooks.Open "e:\development\test.xls", 0
' Do your thing here...
appExcel.DisplayAlerts = False ' Surpress save dialog box.
appExcel.Quit ' Quit without saving. you can change as you want
Set appExcel = Nothing
in your code
Try
Dim connString As [String] = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & excelFile & ";Extended Properties=Excel 12.0;"
' Create connection object by using the preceding connection string.
objConn = New OleDbConnection(connString)
' Open connection with the database.
objConn.Open()
appExcel.DisplayAlerts = False ' try here!
' Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Sources : http://www.xtremevbtalk.com/showthread.php?t=16007

failed to read the excel to sql database

I want to upload an Excel file and write data to sql server 2008.
The Excel file has 7 sheets and it writes in 7 tables.
Example : (sheetn -> temp_sheetn)
The code is working well but the last sheet is not writing in the last table.
The code is like this:
Partial Class app_UploadData
Inherits System.Web.UI.Page
Dim apps As New MyApps
Dim GlobReg As Integer = 0
Dim GlobOTC As Integer = 0
Private dt As DataTable = Nothing
Public Function xlsInsert(ByVal pth As String) As System.Data.DataTable
Dim strcon As String = String.Empty
If Path.GetExtension(pth).ToLower().Equals(".xls") OrElse Path.GetExtension(pth).ToLower().Equals(".xlsx") Then
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & pth & ";Extended Properties=""Excel 8.0;HDR=YES;"""
Else
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & pth & ";Extended Properties=""Excel 12.0;HDR=YES;"""
End If
Dim strselect As String = "Select * from [Sheet1$]"
Dim exDT As New DataTable()
Using excelCon As New OleDbConnection(strcon)
Try
excelCon.Open()
Using exDA As New OleDbDataAdapter(strselect, excelCon)
exDA.Fill(exDT)
End Using
Catch oledb As OleDbException
Throw New Exception(oledb.Message.ToString())
Finally
excelCon.Close()
End Try
For i As Integer = 0 To exDT.Rows.Count - 1
' Check if first column is empty
' If empty then delete such record
If exDT.Rows(i)("CardNo").ToString() = String.Empty Then
exDT.Rows(i).Delete()
End If
Next
exDT.AcceptChanges()
' refresh rows changes
If exDT.Rows.Count = 0 Then
Throw New Exception("File uploaded has no record found.")
End If
Return exDT
End Using
End Function
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim ds As New DataSet()
Dim XlsConnString As String = String.Empty
Dim DirPath As String = Server.MapPath("~/Temp_Upload/")
Dim fName As String
If (Directory.Exists(DirPath)) Then
For Each fName In Directory.GetFiles(DirPath)
If File.Exists(fName) Then
File.Delete(fName)
End If
Next
End If
If xlsUpload.HasFile Then
Dim fileName As String = Path.GetFileName(xlsUpload.PostedFile.FileName)
Dim fileExtension As String = Path.GetExtension(xlsUpload.PostedFile.FileName)
Dim fileLocation As String = Server.MapPath("~/Temp_Upload/" & fileName)
xlsUpload.SaveAs(fileLocation)
'Check whether file extension is xls or xslx
If fileExtension = ".xls" Then
XlsConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension = ".xlsx" Then
XlsConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension <> ".xls" Or fileExtension <> ".xlsx" Then
lblMessage.Text = "Upload file must be excel !"
Exit Sub
End If
Dim cmd As New SqlCommand : Dim SheetName As String 'Dim dr As SqlDataReader
'Dim tran As SqlTransaction
apps.OpenConnection()
cmd.Connection = apps.oConn
Dim cn As New OleDbConnection(XlsConnString)
Try
cn.Open()
Catch ex As OleDbException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
' It Represents Excel data table Schema.
Dim dt As New System.Data.DataTable()
dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt IsNot Nothing OrElse dt.Rows.Count > 0 Then
For sheet_count As Integer = 1 To dt.Rows.Count - 1
Try
' Create Query to get Data from sheet.
SheetName = dt.Rows(sheet_count)("table_name").ToString()
'Dim da As New OleDbDataAdapter("SELECT * FROM [" & sheetname & "]", cn)
'da.Fill(ds, sheetname)
'Execute a query to erase any previous data from our destination table
cmd.CommandText = "Truncate Table Temp_" & SheetName
cmd.ExecuteNonQuery()
'Series of commands to bulk copy data from the excel file into our SQL table
Dim OleDbConn As OleDbConnection = New OleDbConnection(XlsConnString)
Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [" & SheetName & "]"), OleDbConn)
'Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [Customer$]"), OleDbConn)
OleDbConn.Open()
Dim OleDbRead As OleDbDataReader = OleDbCmd.ExecuteReader()
Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(apps.oConn)
bulkCopy.DestinationTableName = "Temp_" & SheetName
bulkCopy.WriteToServer(OleDbRead)
OleDbConn.Close()
OleDbConn = Nothing
Catch ex As DataException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Next
End If
cn.Close()
cn = Nothing
apps.CloseConnection()
End If
End Sub
End Class
The line that reads
For sheet_count As Integer = 1 To dt.Rows.Count - 1
should either be
For sheet_count As Integer = 0 To dt.Rows.Count - 1
or
For sheet_count As Integer = 1 To dt.Rows.Count
The first one I suspect, but I can't remember if this is a zero based list as I haven't got VB.Net installed here.
Incidentally there's no need to check the file extension is .xls and then to use the Jet provider, Microsoft.ACE.OLEDB.12.0 will work just fine on .xls files.