Using a combo box as switch to load 2 different databases - vb.net

Hello I have a database management program in Visual Studio 2013 that I would like to use a combo box as a switch for loading one database or the other depending on the decision... I managed to do the switch but I am having several problems when editing the databases from VS 2013:
The information entered in those list(Add, Delete)don't update the Access Database, they just update on the datagrid of VS2013...
The DataGrid starts counting at -1 then -2 and so on...
When I hit the Edit button, the program returns me a OleDbException Unhandled...this exception states this : " An INSERT INTO query cannot contain a multi-valued field."
Here are my codes of the edit add and delete buttons respectively, what I am missing?
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
If ComboBox1.SelectedIndex = -1 Then
MsgBox("Please specify a category first.", MsgBoxStyle.Information)
ComboBox1.Focus()
End If
Me.Validate()
Me.ContactsBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Database_de_EmpleadosDataSet)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'category err
If ComboBox1.SelectedIndex = -1 Then
MsgBox("Please specify a category first.", MsgBoxStyle.Information)
ComboBox1.Focus()
End If
'codes for add a new field
ContactsBindingSource.AddNew()
'ContactsBindingSource1.AddNew()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
'code for err category
If ComboBox1.SelectedIndex = -1 Then
MsgBox("Please specify a category first.", MsgBoxStyle.Information)
ComboBox1.Focus()
End If
'code for removing field/row
ContactsBindingSource.RemoveCurrent()
ContactsBindingSource1.RemoveCurrent()
End Sub
And Here is how I made the switch in the combo box:
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.SelectedIndex = 0 Then
Dim dbprovider As String = "PROVIDER = Microsoft.ACE.OleDb.12.0;"
Dim dbsource As String = "DATA SOURCE = \\Mac\Home\Desktop\Dalangs\Database De Empleados.accdb"
DataGridView1.Show()
DataGridView2.Hide()
con.ConnectionString = dbprovider & dbsource
con.Open()
da.GetFillParameters()
con2.Close()
MsgBox("Employees successfully loaded")
ElseIf ComboBox1.SelectedIndex = 1 Then
Dim dbprovider As String = "PROVIDER = Microsoft.ACE.OleDb.12.0;"
Dim dbsource As String = "DATA SOURCE = \\Mac\Home\Desktop\Dalangs\Database De Clientes.accdb"
DataGridView2.Show()
DataGridView1.Hide()
con2.ConnectionString = dbprovider & dbsource
con2.Open()
da2.GetFillParameters()
con.Close()
MsgBox("Clients successfully loaded")
End If
Button4.Visible = True
End Sub
what I am missing? :S

Related

show patients that had a certain type of diagnose

I have a patient database. In that database i have a table "diagnosetypes" and a table with dossiers with a patient that received a certain diagnose.
In my diagnose form i have a list of diagnoses and now i want to add a listbox with a filter on all patients/dossiers that had this certain diagnose when that diagnose is selected in the combobox.
this is my current code
Public Class Diagnoses
Private Sub Diagnoses_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Tbl_DossiersTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Dossiers)
Me.Tbl_DiagnosesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Diagnoses)
Dim dt = Tbl_DiagnosesBindingSource
cboxDiagnose.DataSource = dt
cboxDiagnose.DisplayMember = "Diag_Type"
txtDiagnoseBeschrijving.Text = dt(0)("Diag_Type").ToString
cboxDiagnose.Focus()
End Sub
Private Sub CboxDiagnose_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles cboxDiagnose.SelectionChangeCommitted
txtDiagnoseBeschrijving.Text = DirectCast(cboxDiagnose.SelectedItem, DataRowView)("Diag_Beschrijving").ToString
End Sub
Private Sub CboxDiagnose_Click(sender As Object, e As EventArgs) Handles cboxDiagnose.Click
RefreshData()
End Sub
Private Sub BtnAddDiagnose_Click(sender As Object, e As EventArgs) Handles btnAddDiagnose.Click
FormMakeDiagnoseType.Show()
End Sub
Private Sub RefreshData()
Try
Me.Tbl_DiagnosesBindingSource.Filter = Nothing
Me.Tbl_DiagnosesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Diagnoses)
Catch ex As Exception
MsgBox("Refresh Data Error: " & ex.Message.ToString(),
MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Add New Record Failed!")
End Try
End Sub
End Class
edit: I changed my code to look like this as a way of trying to accomplish it myself , but i won't work.
Private Sub Diagnoses_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\GoogleDrive\EINDWERK VBNET\PatientenDatabase.accdb")
cn.Open()
Dim cmmd As New OleDb.OleDbCommand("SELECT * FROM tbl_Dossiers WHERE OZ_ID.value = cboxDiagnose.text", cn)
Dim dr As OleDb.OleDbDataReader
dr = cmmd.ExecuteReader
Do While dr.Read
lboxPat_Diagcombo.Items.Add(dr("Rel_naam"))
Loop
cn.Close()
found something that works!
defined a binding source in code
then linked the listbox datasource to the binding source
then added following code :
Private Sub Onderzoeken_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Tbl_DossiersTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Dossiers)
Me.Tbl_OnderzoeksTypesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_OnderzoeksTypes)
Dim dt = Tbl_OnderzoeksTypesBindingSource
cboxOnderzoek.DataSource = dt
cboxOnderzoek.DisplayMember = "OZ_TypeOnderzoek"
cboxOnderzoek.ValueMember = "OZ_ID"
rtbBeschrijvingOnderzoek.Text = dt(0)("OZ_TypeOnderzoek").ToString
cboxOnderzoek.Focus()
Private Sub CboxDiagnose_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles cboxOnderzoek.SelectionChangeCommitted
rtbBeschrijvingOnderzoek.Text = DirectCast(cboxOnderzoek.SelectedItem, DataRowView)("OZ_Onderzoeksbeschrijving").ToString
Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\GoogleDrive\EINDWERK VBNET\PatientenDatabase.accdb")
cn.Open()
Dim ssql As String = "Select Rel_ID, tbl_Relaties.Rel_Naam &' ' & Rel_Voornaam as totaleNaam " &
"From tbl_Relaties INNER Join (tbl_Dossiers INNER Join tbl_DossRelatie On " &
"tbl_Dossiers.Dos_ID = tbl_DossRelatie.DR_DossID) ON tbl_Relaties.Rel_ID = tbl_DossRelatie.DR_RelID WHERE OZ_ID = " & cboxOnderzoek.SelectedValue
Dim cmmd As New OleDb.OleDbCommand(ssql, cn)
Dim dr As OleDb.OleDbDataReader
dr = cmmd.ExecuteReader
If dr.HasRows Then
Application.DoEvents()
bs_Relaties.DataSource = dr
lboxOZpatientcombo.DisplayMember = "totaleNaam"
lboxOZpatientcombo.ValueMember = "Rel_ID"
End If
cn.Close()
End Sub
since i added a binding source, the rest was easier to do:
Private Sub lboxOZpatientcombo_DoubleClick(sender As Object, e As EventArgs) Handles lboxOZpatientcombo.DoubleClick
Try
Dim MPF As New MainPatientform
MPF.display(Me, bs_Relaties.Current("rel_id"))
Catch ex As Exception
End Try
End Sub
thanks to all for new insights in this matter.

Compare data table with same column in different table vb.net

I want to create evaluation program to compare two tables (entry and validation) whether they have same data or not. The number of column two tables are same. For Example there are T_A_Entry, T_A_Val, T_B_Entry, T_B_Val, T_C_Entry, T_C_Val, etc.
I have populated all tables in database with combobox. combobox1 to select entry table, combobox2 to select validation table, combobox3 to select column (but this is optional). I can't figure out how to make comparison in each column.
See image of the tables
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
svr = TextBox1.Text
ComboBox1.Items.Clear()
If Button1.Text = " Connected " Then
Button1.Text = "Connect"
cn.Close()
Exit Sub
End If
Call conDB()
Try
cn.Open()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
If cn.State = ConnectionState.Open Then
Button1.Text = "Connected"
comm.CommandText = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' ORDER BY 'TABLE_NAME' ASC"
dr = comm.ExecuteReader
If dr.HasRows Then
ComboBox1.Items.Clear()
ComboBox2.Items.Clear()
While dr.Read()
ComboBox1.Items.Add(dr("TABLE_NAME"))
ComboBox2.Items.Add(dr("TABLE_NAME"))
End While
End If
dr.Close()
cn.Close()
Else
MessageBox.Show("Fail to Connect")
Button1.Text = "Connect"
End If
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim xsql As String
' mencari nama kolom tabel
xsql = " SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME= '" & ComboBox1.Text & "'"
Call conDB()
cn.Open()
comm.CommandText = xsql
dr = comm.ExecuteReader
If dr.HasRows Then
ComboBox3.Items.Clear()
While dr.Read()
ComboBox3.Items.Add(dr.Item(0))
End While
End If
dr.Close()
cn.Close()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Me.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Call FillGrid(ComboBox1.Text, ComboBox2.Text, ComboBox3.Text)
End Sub
Private Sub FillGrid(ByVal tabelEntry As String, ByVal tabelValidasi As String, ByVal variabel As String)
Dim ds As New DataSet()
'helpp....
End Sub

No New Row Entry Added to Access Backend

so I made this code which is supposed to update the Delivery table in my MS Access database. The code runs fine and even says that data entry is successful, but upon checking the database file no new row entry is made.
Public Class NewDelivery
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim con As New OleDb.OleDbConnection
Public Shared stxtboxsupsel As TextBox
Public Shared supnum As String
Public Shared dgvitems As DataGridView
Private Sub NewDelivery_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "MM/dd/yyyy"
End Sub
Private Function OpenDBConnection()
If My.Settings.DatabaseLoc = "" Then
Dim directory As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Return "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & directory & "\IE156.mdb"
Else
Return "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & My.Settings.DatabaseLoc
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
My.Forms.ManageInventory.Show()
Me.Close()
End Sub
Private Sub btnSelSupp_Click(sender As Object, e As EventArgs) Handles btnSelSupp.Click
My.Forms.SelectSupplier.Show()
stxtboxsupsel = txtboxsupsel
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
con.ConnectionString = OpenDBConnection()
con.Open()
Dim sql As String = "INSERT INTO Delivery(ItemPurchDate,SupNum) VALUES (#ItemPurchDate,#SupNum)"
Dim cmd As New OleDb.OleDbCommand(sql, con)
cmd.Parameters.AddWithValue("#ItemPurchDate", DateTimePicker1.Text)
cmd.Parameters.AddWithValue("#SupNum", supnum)
con.Close()
Me.Close()
MsgBox("New Delivery Recorded")
End Sub
The Delivery Table has 3 columns namely ItemPurchNum (Primary Key and Autonumber), ItemPurchDate(date/time) and SupNum(Number and has a many to one relationship with SupNum from my Supplier table).
I had no trouble adding new rows in my other forms following the similar code. Any thoughts on why it won't add a new row? Thank you in advance!
thanks for your help. Noticed that I skipped a line cmd.ExecuteNonQuery(), and now it works!

Datagridview and access database only updates after clicking a different row

I am reading an access database and populating the info in datagridview. My form has a DGV, and 3 buttons.
Button one copies the selected row to a datetimepicker control.
Button two copied the updated datetimepicker value back to the DVG
Button three does an update (writes the info back to the database).
My issue is that the info only gets updated in the database if I select a different row before hitting button three. I am not getting any error message in either case.
Below is my code. The database only has 2 columns (name and DOB - which is date/time).
Public Class Form1
Dim dbConn As New OleDb.OleDbConnection
Dim sDataset As New DataSet
Dim sDataAdapter As OleDb.OleDbDataAdapter
Dim sql As String
Dim iTotalRows As Integer
Dim sShipTypeFilter As String
Dim sBuildingFilter As String
Dim sCustSuppFilter As String
Dim sStatusFilter As String
Dim sDayFilter As String
Dim dv As New DataView
Sub myDBConn()
dbConn.ConnectionString = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\terry\Documents\Database1.accdb"
Debug.Print("Start:" & DateAndTime.Now.ToString)
dbConn.Open()
sql = "select * from TableX"
sDataAdapter = New OleDb.OleDbDataAdapter(Sql, dbConn)
sDataAdapter.Fill(sDataset, "MyTable")
dbConn.Close()
iTotalRows = sDataset.Tables("MyTable").Rows.Count
Debug.Print("Rows from Access:" & iTotalRows)
Debug.Print("End:" & DateAndTime.Now.ToString)
End Sub
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Call myDBConn()
Debug.Print("DVG1 row count before binding:" & DataGridView1.Rows.Count)
'dv = New DataView(sDataset.Tables(0), "Shipment = 'Regular' and Building = 'CSE'", "Company DESC", DataViewRowState.CurrentRows)
dv = sDataset.Tables(0).DefaultView
Debug.Print("DataView count:" & dv.Count)
DataGridView1.DataSource = dv
Debug.Print("DVG1 Rows:" & DataGridView1.Rows.Count)
DataGridView1.Columns("DOB").DefaultCellStyle.Format = "hh:mm tt"
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
dtp1.Value = DataGridView1.SelectedRows(0).Cells("DOB").Value
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
DataGridView1.SelectedRows(0).Cells("DOB").Value = dtp1.Value
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Debug.Print("switched row")
Me.Visible = False
Dim sqlcb As New OleDb.OleDbCommandBuilder(sDataAdapter)
sDataAdapter.Update(sDataset.Tables("MyTable"))
Me.Close()
End Sub
End Class
Before updating you need to Endedit. This means you need to add Endedit for the datagridview.
So this will be your code:
Debug.Print("switched row")
Me.Visible = False
Dim sqlcb As New OleDb.OleDbCommandBuilder(sDataAdapter)
Datagridview1.EndEdit()
sDataAdapter.Update(sDataset.Tables("MyTable"))
Me.Close()
EDIT1:
Dim dt As New DataTable
dbConn.Open()
sDataset.Tables.Add(dt)
sDataAdapter = New OleDbDataAdapter("Select * from TableX", dbConn)
sDataAdapter.Update(dt)
dbConn.Close()
I figured it out - thanks Stef for putting me on the right track.
My DGV is only updated programmatically (not by user edits) so I updated the code for button 2 to set the editmode, begin editing, update the selected DVG row and end editing:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically
DataGridView1.BeginEdit(True)
DataGridView1.SelectedRows(0).Cells("DOB").Value = dtp1.Value
DataGridView1.EndEdit()
End Sub
After doing this modification - my datadapter.update command works!!

Validating a command according to user level

I am trying to use this code to validate the delete operation. It should only execute if the code entered in the input box is for a super admin but it is returning an error "There is no row at position 1". Anyone who can give a better code structure will be greatly appreciated.
Private Sub btnD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnD.Click
dbProvider = "Provider=Microsoft.Ace.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Blessing\Documents\IBCARIP.accdb;Persist Security Info=False"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "select UserID from Users where UserID = 'dlass8504'"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds2, "IBCARIP")
con.Close()
If InputBox("Please input your UserID to complete operation").ToString <> ds2.Tables("IBCARIP").Rows(inc).Item("UserID").ToString Then
MsgBox("You do not posess sufficient previlegies to perfom this operation..!", MsgBoxStyle.Critical)
ElseIf MsgBox("Do you really want to Delete this Record?", MsgBoxStyle.YesNo) = MsgBoxResult.Ok Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("IBCARIP").Rows(inc).Delete()
MaxRows = MaxRows - 1
inc = 0
da.Update(ds, "IBCARIP")
navigaterecords()
End If
End Sub
For idea only ..
Private Sub Form_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'here's code for retrieving level
btnD.Enabled = iif(Level < 3, True, False) '-- this will disabled your delete button
End Sub
Private Sub btnD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnD.Click
Dim r As MsgBoxResult
r = Msgbox("Do you really want to Delete this Record?", MsgBoxStyle.YesNo)
If r = MsgBoxResult.Yes Then
'erasing here
End If
End Sub