unable add 2nd data to Access database using the GUI button - vb.net

i have try to add some data into the access database VIA VB2008, when i pull in no issue using their original function, where there is add, delete and save button on top of it, but when i am creating the function on the button, found that 1st data able to add, second data unable to add, it show "too many field to defined" appreciate someone can help out, i go through many link, i am copy exactly what they have done.
i have tried remove the ID (auto generate number in access) but still fail. no article on it
If Button2.Text = "New" Then
Try
BEFOREBindingSource.AddNew()
MsgBox("successful")
Catch ex As Exception
MsgBox("Error during Add")
Exit Sub
End Try
ElseIf Button2.Text = "Save" Then
Try
'Me.BEFOREBindingSource.EndEdit()
' Me.TableAdapterManager.UpdateAll(Me.MPCINSPECTION2DataSet)
BEFOREBindingSource.EndEdit()
BEFORETableAdapter.Update(MPCINSPECTION2DataSet.BEFORE)
Catch ex As Exception
MsgBox("Error during save")
Exit Sub
End Try
End if

Related

Use MsgBox to open form to new record or delete record from continuous form if the record does not already exist

I have a form with a continuous subform that is used to "check out" items. If an item is entered that is not currently in the items table, an error fires.
I would like to create a custom msgbox that will allow the user to select the next action; either open a form to enter the new item (along with a number of details about the item) or to delete the row.
I have been able to fire the msgbox code and successfully open the form to enter a new item, but I cannot get the row to delete from the subform OR use SetProperty to return the value to null.
Here is the current code to launch the MsgBox which is triggered BeforeUpdate, OnError from the control in question.
Function MsgBox_NewAsset()
MsgBoxResult = MsgBox("The Asset Number you entered is not in the system. Would you like to enter this as a new asset?", 4 + vbQuestion, "New Asset?")
If MsgBoxResult = 6 Then
DoCmd.SetWarnings False
DoCmd.OpenForm "Asset Details", , , "AssetID=0"
DoCmd.SetWarnings True
Else
DoCmd.SetProperty("AssetID",acPropertyValue,"")
End If
End Function
When setting the SetProperty command using:
DoCmd.SetProperty("AssetID",acPropertyValue,"")
I get a compile error:
Expected: =
I'm relatively new to VBA, so not entirely sure what this indicates.
Try DoCmd.RunCommand acCmdUndo rather than DoCmd.SetProperty(...)
The form is sitting on an uncommitted, new record that can't be committed. To roll it back, use Undo.

How to catch concurrency exception for a shared local database (SQL Server Compact | .sdf) in Visual Basic?

I am writing a programm that allows two users to access the same local database (.sdf) in a shared folder. The database consists of tasks for the employee. One user (Master) adds and edits those tasks, the other one (Slave) marks them as done/undone and updates the list.
The two of them should be allowed to work simultaneously. I.e. Master adds a new task, Slave finishes one task, updates the list and finds the new one immediately.
When a database query is executed an instance of a module is created that opens the database, executes the SQL-query (Select, Update, Delete, ...) and closes it. This is how the VB module looks like:
Public Sub ExecQuery(Query As String)
Try
SQLCon.Open()
SQLCmd = New SqlCeCommand(Query, SQLCon) 'Create SQL command
' Load Parameters into SQL Command
Params.ForEach(Sub(x) SQLCmd.Parameters.Add(x))
Params.Clear() ' Clear Parameter List
' Execute Command, Fill Dataset and close database
SQLDS = New DataSet
SQLCon.Close()
Catch ex As Exception
Exception = ex.Message
End Try
If SQLCon.State = ConnectionState.Open Then SQLCon.Close()
End Sub
If have to admit, that I took the code-snippet from a tutorial.
Now an update of the DataGridView would look like this:
Public Sub GetEntry()
Dim ii As Integer = 0
grdData.Rows.Clear() 'empty GridDataView
SQL.ExecQuery("SELECT * FROM Tasks)
grdData.Rows.Add(n)
For Each r As DataRow In SQL.SQLDS.Tables(0).Rows
grdData.Item(0, ii).Value = r(0)
grdData.Item(1, ii).Value = r(1)
grdData.Item(2, ii).Value = r(2)
' ...
ii += 1
Next
If SQL.Exception <> "" Then
MsgBox(SQL.Exception)
End If
End Sub
The problem is that when Master and Slave both perform an SQL.ExecQuery(String) command, they are accessing the same .sdf which should not be possible, right? I expected something like "Cannot open database.sdf, as it is currently accessed by another user". I then would like to let the script wait for one second and retry. But instead I get "Error: Index out of range". So I assume, the code tries to read all entries but it can't.
Does anybody know how to catch this exception? I read about a
Data.DBConcurrencyException
but I don't know if it's the thing I am looking for and how to use it.

How to update an active directory using userform textboxes

I have a program which loads data from text files contained in directories back into text boxes on the user interface.
What I want to achieve is:
if the user changes a text of one of the text boxes and then clicks an "Update" button, the old record and its holding directory should be deleted the new record, saved in a new directory.
The code I am using now is:
Dim dtl = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Cake Orders\" & TextBox1.Text))
'Delete the culled record
Try
If Directory.Exists(dtl.FullName) Then
Dim oDirectory As New DirectoryInfo(dtl.FullName)
If oDirectory.GetFiles.Count > 0 Then
For Each oFile As FileInfo In oDirectory.GetFiles
oFile.Delete()
Next
End If
If oDirectory.GetDirectories.Count > 0 Then
For Each oDir As DirectoryInfo In oDirectory.GetDirectories
oDir.Delete(True)
Next
dtl.Delete()
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
'Continue to save the updated record
The above code just saves the current data in a new directory (which is fine), but does not delete the original directory like I want it to; that is to say that my code is not executing the above delete routine.
How can I achieve my objective? I am using Visual Basic 2010 Express. Thank you.
What I would suggest is that you find a way to walk around your problem, to get your program to do what you want it to.
Granted, some may provide you with some more advanced, Einstein-esque codes that will do what you want and by all means, I would encourage you try them out. In the meantime, why not consider this approach?
During the cull event when you load data from the root directory, why not save the name of your sub-directory to a redundant textbox so that your delete routine can ‘see’ it and execute the delete routine before the rest of your code, which you say works fine, runs?
This is to say:
Dim dtl = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Cake Orders\" & RedundantTextbox.Text))
Surely, you would not be charged with finding a cheeky way to avoid being eaten alive by software programming which sometimes can be a brain-eating dinosaur.

Capturing Popups, Alerts, and Exceptions from Excel with VB 2010

This is my first time posting in stackoverflow. I started learning VB 2010 yesterday (though I do know some Ruby) and have googled this problem a lot but haven't found much.
I've written a program that takes a CSV list of filepaths (all .XLS files) and attempts to open them. These excel workbooks were flagged as unreadable by another program; my program tries to capture the warning, popup, or exception that caused the error. It works for most exceptions (password protected, Unreadable Content, Dangerous File, etc.), but some popups that require you to click the 'OK' button to continue aren't caught. Maybe they aren't categorized as Exceptions or something, I'd love to know. It would be great to at least get the text form of them. Here is my script:
Private Sub runReportButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles runReportButton.Click
Dim Exl As New Excel.Application()
Exl.Visible = False
Exl.DisplayAlerts = False
For Each row As DataGridViewRow In dgvReport.Rows
If Not IsNothing(row.Cells(0).Value) Then
If row.Cells(0).Value.ToString.Contains(".xls") Then
Try
'Open the workbook and attempt to catch the error!'
'Use bogus passwords to cause Password Protected Error, Readonly disabled so the Password popup shows. Update links disabled because it wasn't being caught anyways'
Dim wb As Excel.Workbook = Exl.Workbooks.Open(row.Cells(0).Value.ToString, [ReadOnly]:=False, [WriteResPassword]:="WWWWWWWWWWW", [Password]:="WWWXWXWWWXW", [UpdateLinks]:=False)
row.Cells(4).Value = "Could not catch an error :("
wb.Close(0)
dgvReport.Refresh()
Catch ex As Exception
'Writes the Exception Message to the data grid view'
row.Cells(4).Value = ex.Message
End Try
ProgressBar1.Value += 1
End If
End If
Exl.Quit()
Next row
dgvReport.Refresh()
End Sub
The reason I'm having a problem is that certain popups only occur when I open the file manually. Even with Excel set to visible and display alerts on, programmatically the file opens and closes without any popups. One particular warning is the following:
"One or more worksheets in this workbook have names that contain square brackets:[]. To avoid unexpected results when referencing these worksheets, remove any square brackets from their names."
It doesn't seem like a fatal error, but it causes the other program to flag it as unreadable because we cannot be certain of the integrity of the contents (i.e. the unexpected results). So my need isn't to ignore these popups or improve the other program, it's to capture this pesky popup message. If anyone can shed any light on the duality of this popup's behavior or provide a different approach to capturing alerts it would be much appreciated!

No Access to an mdb database file after copying the file

I have the following code where I make an copy of my database that I use. the code executes 100% but the problem I have is I'm not able to access my database afterward.I get a "Cannot start your application. The workgroup information file is missing or opened exclusively by another user." and so if I restart the application it all works fine again.
I'm certain the reason is because I can only access that database using a specific account name and password which is not account I'm logged in with.
What i want to try is to default that database mdb to the point where no user is accessing it, or to reassign the the only account name that can access it to that database mdb.
Any ideas, will be enormously appreciated? I've tried playing around with file security but had no luck.
Private Sub cmdBackup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBackup.Click
BackupDialogDB.DefaultExt = ".mdb"
BackupDialogDB.InitialDirectory = "c:\"
'SaveFileDialog1.ShowDialog()
If BackupDialogDB.ShowDialog() = Windows.Forms.DialogResult.OK Then
Try
Dim sDBFile As String = Application.StartupPath + "\VFMS_DB.mdb"
Dim sBackUpFile As String = BackupDialogDB.FileName
'First check the file u want to compact exists or not
If File.Exists(sDBFile) Then
If Not File.Exists(sBackUpFile) Then
File.Copy(sDBFile, sBackUpFile)
Else
File.Delete(sBackUpFile)
File.Copy(sDBFile, sBackUpFile)
End If
MessageBox.Show("The database was successfully backedup to: " + sBackUpFile , "Database Backedup", MessageBoxButtons.OK, MessageBoxIcon.Information)
sDBFile = ""
Else
MessageBox.Show("There is no database to backup. Please restore from a backup", "Database Backup Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
You should also copy and/or restore the workgroup information file.
Do you have write permission in the target directory? Access needs to create a .ldb file along side the .mdb.
Otherwise, you can try some of the stuff here:
http://www.xlinesoft.com/asprunnerpro/docs/error_the_microsoft_jet_database_engine_cannot%20open%20the%20file%20(unknown).htm
Was the Database open when you copied it? Access creates lock files, *.ldb in the same directory the database is in, you might want to check for that file before you copy the database.