I tried this code first before copying it to my main project (I created new project to test the codes first):
Private Sub posBtn_Click(sender As Object, e As EventArgs) Handles posBtn.Click
On Error GoTo wewe
If posText.Text = "" Then
Call notFound()
Exit Sub
Else
Dim cantFind As String = posText.Text
EmployeesRecordBindingSource.Filter = "(Convert(#_of_Employees, 'System.String') LIKE '" & posText.Text & "')" & "OR (last_name LIKE '" & posText.Text & "') OR (first_name LIKE '" & posText.Text & "')" & "OR (mi LIKE '" & posText.Text & "') OR (position LIKE '" & posText.Text & "')"
If EmployeesRecordBindingSource.Count <> 0 Then
With DataGridView2
.DataSource = EmployeesRecordBindingSource
End With
Else
MsgBox(cantFind & vbNewLine & "The search item was not found!", MsgBoxStyle.Information, "Hey boss")
EmployeesRecordBindingSource.Filter = Nothing
With DataGridView2
.ClearSelection()
.DataSource = EmployeesRecordBindingSource
End With
End If
End If
lul:
Exit Sub
wewe:
MsgBox("Error Number " & Err.Number & vbNewLine & "Error Description " & Err.Description, MsgBoxStyle.Critical, "Reset Error!")
Resume lul
End Sub
In my sample project, this is working. But when I copied it to my main project and run, I got this error: The expression contains invalid date constant '#_ofE_Employees, 'Sytem.String') LIKE '1')OR and so on... Did I missed something? Btw, it is for searching in datagridview. I have also private sub for reset, notfound.
Fields cannot start with the # as it is used for dates.
You might reconsider using signs and numbers when creating fields and variables in both your platform and database because there are chances those are reserved.
Related
I apologize in advance if this has been answered before. I searched for it but could not find anything explaining this particular issue.
I'm getting the OleDb exception 0x80004005 - Cannot open any more tables while reading a large Excel spreadsheet. It parses around 2000 records correctly than breaks.
I searched for this error, which is related to a limit of 2048 tables being open at a given time. I cannot see where my code is wrong, and I think it is, but I need a fresh pair of eyes looking at me to point me out what I'm missing.
This is the code - As you can see, I am closing the reader ReaderExcelProgramsColumn
What am I not seeing?
If strSpreadSheetFullPathLowCase.Contains(".xlsx") Then
strConnectionStringExtendedParameters = ";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;Mode=Read;Readonly=True"";"
ElseIf strSpreadSheetFullPathLowCase.Contains(".xlsm") Then
strConnectionStringExtendedParameters = ";Extended Properties=""Excel 12.0 Macro;HDR=YES;IMEX=1;Mode=Read;Readonly=True"";"
End If
Dim intColumStartLocator As Integer = 0
Dim strConnectionStringExcel = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & txtFilePathOpenExcel.Text & strConnectionStringExtendedParameters
Dim strProgramID As String = Nothing
Dim strMachinePrefix As String = Nothing
Dim strProgramFileExtensionFromExcel As String = Nothing
Dim strLastFileName As String = Nothing
Dim strLastProgramID As String = Nothing
Dim strFullFilePath As String = Nothing
Dim sqlExcelConnection As OleDbConnection = Nothing
Try
'/////////////////////////////////////////////
'// Open the connection with the Excel File //
'/////////////////////////////////////////////
lblStatus.Text = "Opening connection with MS-Excel..."
Application.DoEvents()
sqlExcelConnection = New OleDbConnection(strConnectionStringExcel)
sqlExcelConnection.Open()
Catch ex As Exception
If (sqlExcelConnection.State = ConnectionState.Open) Then
sqlExcelConnection.Dispose()
End If
ErrorToReadFromMSExcel(ex.ToString, System.Reflection.MethodInfo.GetCurrentMethod.ToString, True)
Exit Sub
End Try
Try
Dim strProgramsQuery As String = "SELECT" & vbNewLine &
"[" & cboxExcelCIMCODBFieldProgram.Text & "]" & vbNewLine &
"FROM [" & cboxExcelTabName.Text & "$]"
Dim Query As String = String.Empty
Dim sqlSelectColumnsExcelPrograms As New OleDbCommand(strProgramsQuery, sqlExcelConnection)
Dim ReaderExcelProgramsColumn As OleDbDataReader = sqlSelectColumnsExcelPrograms.ExecuteReader
Do While ReaderExcelProgramsColumn.Read()
If ReaderExcelProgramsColumn.HasRows Then
strProgramID = Trim(UCase(ReaderExcelProgramsColumn.GetValue(0).ToString))
Dim strQuery As String = "SELECT" & vbNewLine &
"hdrfullprefix" & vbNewLine &
"FROM " & strCustomNameForHeaderSettingsTable & " AS slb" & vbNewLine &
"INNER JOIN " & strTableMchGroups & " AS mg" & vbNewLine &
"WHERE mg." & strMchGroupID & " = slb.machidncbase" & vbNewLine &
"AND mg." & strMchGroup & " = '" & cboxCIMCOMachineToMigrate.Text & "'" & vbNewLine &
"ORDER BY id DESC" & vbNewLine &
"LIMIT 1"
strMachinePrefix = RunBasicQueryReturnIsStringOnNCBase(strNCBaseConnectionString, strQuery)
If strProgramID <> String.Empty Then
lblStatus.Text = "Extracting program '" & strProgramID & "' from the spreadsheet..."
Application.DoEvents()
arrProgramsInTheSpreadSheet.Add(strProgramID)
arrProgramsPrefixes.Add(strMachinePrefix)
End If
If arrProgramsInTheSpreadSheet.Count = 0 Then
MessageBox.Show(Me, "Could not find programs in the spreadsheet in the column '" & cboxExcelCIMCODBFieldProgram.Text & "', tab '" & cboxExcelTabName.SelectedItem.ToString & "' of the selected spreadsheet!" _
& vbNewLine & vbNewLine & "Please check if the column name selected for program extraction is correct in the spreadsheet and try again.", "Could not find programs in the selected spreadsheet!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
Else
ReaderExcelProgramsColumn.Close()
MessageBox.Show(Me, "Could not find programs in the spreadsheet in the column '" & cboxExcelCIMCODBFieldProgram.Text & "', tab '" & cboxExcelTabName.SelectedItem.ToString & "' of the selected spreadsheet!" _
& vbNewLine & vbNewLine & "Please check if the column name selected for program extraction is correct in the spreadsheet and try again.", "Could not find programs in the selected spreadsheet!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
strLastProgramID = strProgramID
Application.DoEvents()
Loop
ReaderExcelProgramsColumn.Close()
sqlSelectColumnsExcelPrograms.Dispose()
'Close connection to release memory
ReaderExcelProgramsColumn.Close()
sqlSelectColumnsExcelPrograms.Dispose()
sqlExcelConnection.Dispose()
'Open a new connection
sqlExcelConnection = New OleDbConnection(strConnectionStringExcel)
sqlExcelConnection.Open()
lblStatus.Text = "Starting data extraction... Please wait..."
Application.DoEvents()
'*** Sort the array ***
arrProgramsInTheSpreadSheet.Sort()
'*** Capture Program Extensions ***
For i As Integer = 0 To arrProgramsInTheSpreadSheet.Count - 1
strProgramsQuery = "SELECT TOP 1 [" & strProgramFileExtensionNoPunctuation & "] FROM [" & cboxExcelTabName.Text & "$] WHERE [" & cboxExcelCIMCODBFieldProgram.Text & "] = '" & arrProgramsInTheSpreadSheet.Item(i) & "'"
sqlSelectColumnsExcelPrograms = New OleDbCommand(strProgramsQuery, sqlExcelConnection)
ReaderExcelProgramsColumn = sqlSelectColumnsExcelPrograms.ExecuteReader
Do While ReaderExcelProgramsColumn.Read()
'*****************************************************************************
'** The exception 0x80004005 - Cannot open any more tables occurs somewhere **
'** here, even after I closed the connection between the loops. **
'*****************************************************************************
If ReaderExcelProgramsColumn.HasRows Then
strLastProgramID = arrProgramsInTheSpreadSheet.Item(i)
lblStatus.Text = "Extracting the extension of the program '" & arrProgramsInTheSpreadSheet.Item(i) & "' from the spreadsheet..."
Application.DoEvents()
strProgramFileExtensionFromExcel = Trim(UCase(ReaderExcelProgramsColumn.GetValue(0).ToString))
tupleProgramsAndExtensions.Add((arrProgramsInTheSpreadSheet.Item(i), strProgramFileExtensionFromExcel))
Else
ReaderExcelProgramsColumn.Close()
MessageBox.Show(Me, "HeaderPuncher could not find programs in the spreadsheet in the column '" & cboxExcelCIMCODBFieldProgram.Text & "', tab '" & cboxExcelTabName.SelectedItem.ToString & "' of the selected spreadsheet!" _
& vbNewLine & vbNewLine & "Please check if the column name selected for program extraction is correct in the spreadsheet and try again.", "Could not find programs in the selected spreadsheet!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
Loop
Next
ReaderExcelProgramsColumn.Close()
sqlSelectColumnsExcelPrograms.Dispose()
sqlExcelConnection.Dispose()
Thanks!
The answer is what some people mentioned in the comments: The usage of Using / End Using instead of the archaic approach I was using.
Many thanks, everyone!
When I clear the search box in the form, the table shows the same info (I want the table to show the original one, without any query).
Code:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If TextBox14.Text = "" Then
Call NotFound()
Exit Sub
Else
CustomerInfo1BindingSource.Filter = "(Convert(ID, 'System.String') LIKE '" & TextBox14.Text & "')" &
"OR (CustomerName LIKE '" & TextBox14.Text & "') OR (CustomerNumber LIKE '" & TextBox14.Text & "')" &
"OR (OrderDate LIKE '" & TextBox14.Text & "')"
If CustomerInfo1BindingSource.Count <> 0 Then
With CustomerInfo1DataGridView
.DataSource = CustomerInfo1BindingSource
End With
Else
MsgBox("Not Found!")
CustomerInfoBindingSource.Filter = Nothing
End If
End If
End Sub
If I've read the question correctly it appears that you're saying this:
You add a search term to TextBox14 which is then applied to the CustomerInfo1BindingSource.Filter and in turn that filters CustomerInfo1DataGridView as expected
You remove the search term from TextBox14 and click the button again
The filtered CustomerInfo1DataGridView remains untouched rather than showing everything
If that is the case I can see that code flow isn't exactly what you're expecting. Change it to be something like:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If TextBox14.Text = "" Then
CustomerInfoBindingSource.Filter = Nothing
MsgBox("Not Found!")
Else
CustomerInfo1BindingSource.Filter = "(Convert(ID, 'System.String') LIKE '" & TextBox14.Text & "')" &
"OR (CustomerName LIKE '" & TextBox14.Text & "') OR (CustomerNumber LIKE '" & TextBox14.Text & "')" &
"OR (OrderDate LIKE '" & TextBox14.Text & "')"
If CustomerInfo1BindingSource.Count <> 0 Then
With CustomerInfo1DataGridView
.DataSource = CustomerInfo1BindingSource
End With
End If
End If
End Sub
As it stands with your code the lineCustomerInfoBindingSource.Filter = Nothing is not being hit because there is no search term in TextBox14. Instead it's calling this NotFound() method which we don't have visibility of, and then exiting the method.
It might be worth also reading up on the official documentation. You can call RemoveFilter on a BindingSource:
CustomerInfoBindingSource.RemoveFilter()
I am using an Access form to search a table using different textboxes, i.e. Title, Author, Date etc.
Right now I use this code to perform the search, and update a subform with the results:
Private Sub sFindData(strTitle As String, dtmDate As String, strAuthor As String)
On Error Go to E_Handle
Dim strSQL As String
If Len(strTitle) > 0 Then
strSQL = strSQL & " AND Title LIKE '*" & strTitle & "*' "
End If
If (IsDate(dtmDate)) Then
strSQL = strSQL & " AND DocumentDate=" & Format(Me!txtDate, "\#mm\/dd\/yyyy\#")
End If
If Len(strAuthor) > 0 Then
strSQL = strSQL & " AND Author LIKE '*" & strAuthor & "*' "
End If
If Left(strSQL, 4) = " AND" Then
strSQL = " WHERE " & Mid(strSQL, 5)
End If
strSQL = "SELECT Title, DocumentDate, Author FROM tblDocument" & strSQL
Me!sSubTable.Form.RecordSource = strSQL
sExit:
On Error Resume Next
Exit Sub
E_Handle:
MsgBox Err.Description & VbCrLf & VbCrLf & Err.Source & VbCrLf & VbCrLf & "sFindData", vbOKOnly + vbCritical, "Error: " & Err.Number
And I use this code to call sFindData through textboxes on the form:
Private Sub txtTitle_Change()
Call sFindData(Nz(Me!txtTitle.Text, ""), Nz(Me!txtDate, #12/31/2099#), Nz(Me!txtAuthor, "")
End Sub
I have a Change Sub for every textbox in the main form, each bound to its own field through the same code shown above.
My problem is, I sometimes need to search multiple criteria of the same type (two different document titles for example), and I want to be able to do it in one field if possible, i.e. separate the two criteria with a comma (Title#1, Title#2) and have the code search both of these criteria and show the results on the subform
Thanks in advance
Good Day! I'm clueless on visual studio. Please Help me.
I have a datagridview that has database access file.
its bound to textboxes
now i have a search button that has a textbox too.
it runs fine but it needs to input the complete name.
I want it to be when you just input a letter it shows all the names that has/have that letter.
for example if i type "A" all names in the the database that has letter "A" on it will show.
but in this case
if i type "AGING" it will say cant find. It must be "AGING OVEN" for it to show the result.
here is my code.
please help thanks
Private Sub SearchBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchBtn.Click
On Error GoTo SearchErr
If SearchTxtbox.Text = "" Then
Exit Sub
Else
Dim cantFind As String = SearchTxtbox.Text
TOOLSANDEQUIPMENTBindingSource.Filter = "(CONVERT(ID, 'System.String') like '" & SearchTxtbox.Text & "')" & _
"OR ([TOOL and EQUIPMENT] like '" & SearchTxtbox.Text & "') OR ([QUANTITY] like '" & SearchTxtbox.Text & "')" & _
"OR ([ITEM NO] like '" & SearchTxtbox.Text & "')" & _
"OR ([PART NO] like '" & SearchTxtbox.Text & "')" & _
"OR ([DATE MODIFIED] like '" & SearchTxtbox.Text & "')"
If TOOLSANDEQUIPMENTBindingSource.Count <> 0 Then
With TEDataGridView
.DataSource = TOOLSANDEQUIPMENTBindingSource
End With
Else
MsgBox("--> " & cantFind & vbNewLine & _
"The search item was not found.", _
MsgBoxStyle.Information, "Hey Boss!")
TOOLSANDEQUIPMENTBindingSource.Filter = Nothing
With TEDataGridView
.ClearSelection()
.ReadOnly = True
.MultiSelect = False
.DataSource = TOOLSANDEQUIPMENTBindingSource
End With
End If
End If
ErrEx:
Exit Sub
SearchErr:
MsgBox("Error Number " & Err.Number & vbNewLine & _
"Error Description " & Err.Description, MsgBoxStyle.Critical, _
"Reser Error!")
Resume ErrEx
End Sub
I am working on a form on Access. It is supposed to insert data into a table, but I keep getting error 3464.
I am a little new to Visual Basic. This was previously working, but no longer. I am using SQL Server as a back-end. The connection works and it was inserting new rows. I have looked online but have not found a comprehensive explanation of this error.
Private Sub mSubmitButton_Click()
CurrentDb.Execute "INSERT INTO dbo_Reporting_Table([Date], Vendor, Ordered_By, Picked_Up_By, Reported_By) " & _
" VALUES('" & Me.mDate & "','" & Me.mVendor & "','" & Me.mOrdered_By & "','" & _
Me.mPicked_Up_By & "','" & Me.mReported_By & "')"
CurrentDb.Execute "INSERT INTO dbo_Items_Table([PO#], [Item], [Price], [Equipment], [Quantity]) " & _
" VALUES(" & Me.mPONumber & ",'" & Me.mItemInput0 & "'," & Me.mPriceInput0 & ",'" & _
Me.mEquipmentInput0 & "'," & Me.mQuantityInput0 & ")"
Me.mItemInput0 = ""
Me.mPriceInput0 = ""
Me.mEquipmentInput0 = ""
Me.mQuantityInput0 = ""
Me.mDate = ""
Me.mVendor = ""
Me.mOrdered_By = ""
Me.mPicked_Up_By = ""
Me.Requery
Exit Sub
Error_PopupMessage:
'Response = MsgBox(Message, vbOKOnly + vbInformation, "Form Entry Hint", "help", "1000")
Exit Sub
End Sub
Any advice on what I might be doing wrong would be greatly appreciated.
My problem was that, in the form, I was not entering all of the required fields before I pressed submit. I now have an if statement that ends the process if the required fields are null. Hope this might be of use to someone.
If Eval(IsNull(Me.mDate.Value) Or IsNull(Me.mVendor.Value) Or IsNull(Me.mPicked_Up_By.Value) Or IsNull(Me.mReported_By.Value)) Then
MsgBox " Make sure you have entered the Date, Vendor, Purchaser, and signed the form. "
Exit Sub
ElseIf Eval(IsNull(Me.mItemInput0.Value) Or IsNull(Me.mEquipmentInput0.Value) Or IsNull(Me.mPriceInput0.Value)) Then
MsgBox " Please enter atleast one complete row of an item for the PO. "
Exit Sub
Else
End If