Insert multiple records with multiple tables having the same ID into a table using DAO in Access - sql

(1) I have 4 tables (A-Sched,B-Trans,(C-ItemRecep and D-ItemPharm)) with one Lookup table called D-TransDetail. Below is the relationship diagram and the DAO record set for storing records.
Public Sub RecpSchedule1()
'Consultation ONLY
Dim db As DAO.Database
Dim rs As DAO.Recordset, rt As DAO.Recordset, rd As DAO.Recordset, ri As DAO.Recordset
Dim lngTransId As Long
Dim lngItemRecepId As Long
Set db = CurrentDb
Set rs = db.OpenRecordset("Sched")
Set rt = db.OpenRecordset("Trans")
Set ri = db.OpenRecordset("ItemRecep")
Set rd = db.OpenRecordset("TransDetail")
lngItemRecepId = Nz(DMax("ID", "ItemRecep"), 0) + 1 'Next ItemRecep ID
lngTransId = Nz(DMax("ID", "Trans"), 0) + 1 'Next Trans ID
With rs
.AddNew
!SDate = Me.txtSchedDate
!PatientName = Me.cmbPatientName
!RegNo = Me.txtRegNo
!DateOfBirth = Me.txtAge
!Gender = Me.txtGender
!PatientClass = Me.PatientClass
!RecepSchedule = True
.Update
End With
With rt
.AddNew
!ID = lngTransId
!SchedRegNo = Me.txtRegNo
![Total_RecepFee] = Me.txtConsFee + ![Total_RecepFee]
.Update
End With
With ri
.AddNew
!ID = lngItemRecepId
!ItemName = "ConsFee"
!Price = Me.txtConsFee.Value
!Dept = "Reception"
.Update
End With
With rd
.AddNew
!TransID = lngTransId
!TransID = DMax("ID", "Trans")
!ItemRecepID = DMax("ID", "ItemRecep")
.Update
End With
rs.Close
rt.Close
ri.Close
rd.Close
Set rs = Nothing
Set rt = Nothing
Set rd = Nothing
Set ri = Nothing
Set db = Nothing
End Sub
Public Sub RecpSchedule2()
Dim db As DAO.Database
Dim rs As DAO.Recordset, rt As DAO.Recordset, rd As DAO.Recordset, ri As DAO.Recordset
Dim lngTransId As Long
Dim lngItemRecepId As Long
Set db = CurrentDb
Set rt = db.OpenRecordset("Trans")
Set ri = db.OpenRecordset("ItemRecep")
Set rd = db.OpenRecordset("TransDetail")
lngItemRecepId = Nz(DMax("ID", "ItemRecep"), 0) + 1 'Next ItemRecep ID
lngTransId = Nz(DMax("ID", "Trans"), 0) + 1 'Next Trans ID
With ri
.AddNew
!ID = lngItemRecepId
!ItemName = "IOPFee"
!Price = Me.txtIOPFee.Value
!Dept = "Reception"
.Update
End With
With rd
.AddNew
!TransID = lngTransId
!TransID = DMax("ID", "Trans")
!ItemRecepID = DMax("ID", "ItemRecep")
.Update
End With
rt.Close
ri.Close
rd.Close
Set rt = Nothing
Set rd = Nothing
Set ri = Nothing
Set db = Nothing
End Sub
(2) I created 2 Queries ("TransQry" and "SubTransQry") from the tables above.
(3) Finally I created a parent form (frmAccount)containing a child "TransForm" which also Parents it's own child "SubTransForm".
This model works perfect when it is only "ItemRecep"(Table C), but the subforms were not reporting correctly on the parent form the moment I introduce the new "ItemPharm"(Table D).
I expected the form to display a new subform transaction Itempharm. (with diff ID i.e 4) containing it's own sub items with Price subtotal. And the Grand Total from the figure above adding up the 2 sub totals.
P.S -Please let me know if my explanation is not understood, I am ready to provide more information

The solution is in the query below:
SELECT DISTINCT Sched.RegNo
,Sched.PatientName
,Sched.DateOfBirth
,Sched.Gender
,Sched.PatientClass
,Sum(ItemRecep.Price) AS SumOfPrice
,Sched.SDate
,Trans.PDate
,Avg(Sched.TotalDiscount) AS AvgOfTotalDiscount
,Sum([ItemRecep] ! [Price]) - Avg([Sched] ! [AmtPaid]) AS Bal
,Avg(Sched.AmtPaid) AS AvgOfAmtPaid
,Trans.RecepTotalPayStatus
,Sum(Trans.Total_PharmFee) AS SumOfTotal_PharmFee
,Sum(Trans.Total_PharmPay) AS SumOfTotal_PharmPay
,Sum(Trans.Pharm_Discount) AS SumOfPharm_Discount
,Sum(Trans.Total_PharmBal) AS SumOfTotal_PharmBal
,Trans.PharmTotalPayStatus
,Sum(Trans.Total_OpticalFee) AS SumOfTotal_OpticalFee
,Sum(Trans.Total_OpticalPay) AS SumOfTotal_OpticalPay
,Sum(Trans.Optical_Discount) AS SumOfOptical_Discount
,Sum(Trans.Total_OpticalBal) AS SumOfTotal_OpticalBal
,Trans.OpticalTotalPayStatus
,Sum(Trans.Total_LabFee) AS SumOfTotal_LabFee
,Sum(Trans.Total_LabPay) AS SumOfTotal_LabPay
,Sum(Trans.Lab_Discount) AS SumOfLab_Discount
,Sum(Trans.Total_LabBal) AS SumOfTotal_LabBal
,Trans.LabTotalPayStatus
,Sum(Trans.Total_SurgeryFee) AS SumOfTotal_SurgeryFee
,Sum(Trans.Total_SurgeryPay) AS SumOfTotal_SurgeryPay
,Sum(Trans.Surgery_Discount) AS SumOfSurgery_Discount
,Sum(Trans.Total_SurgeryBal) AS SumOfTotal_SurgeryBal
,Trans.SurgeryTotalPayStatus
,Sum(Trans.Grand_TotalFee) AS SumOfGrand_TotalFee
,Sum(Trans.Grand_TotalPay) AS SumOfGrand_TotalPay
,Sum(Trans.Grand_TotalDiscount) AS SumOfGrand_TotalDiscount
,Sum(Trans.Grand_TotalBal) AS SumOfGrand_TotalBal
,Trans.Grand_TotalPayStatus
FROM (
Sched INNER JOIN Trans ON Sched.RegNo = Trans.SchedRegNo
)
INNER JOIN (
ItemRecep INNER JOIN TransDetailRecep ON ItemRecep.ID = TransDetailRecep.ItemRecepID
) ON Trans.ID = TransDetailRecep.TransID
GROUP BY Sched.RegNo
,Sched.PatientName
,Sched.DateOfBirth
,Sched.Gender
,Sched.PatientClass
,Sched.SDate
,Trans.PDate
,Trans.RecepTotalPayStatus
,Trans.PharmTotalPayStatus
,Trans.OpticalTotalPayStatus
,Trans.LabTotalPayStatus
,Trans.SurgeryTotalPayStatus
,Trans.Grand_TotalPayStatus
HAVING (
((Sched.SDate) = DATE ())
AND ((Trans.RecepTotalPayStatus) = False)
)
ORDER BY Sched.PatientName;

Related

Strange issue with Datagridview-Rows not displayed

I have a Datagridview connected to a dataset.The problem is that occasionally,when the data is refreshed,it is not displayed in the DGV.The code is:
Private Sub DisplayInDGV()
Dim SQLSet As String
Dim DASet As New OleDb.OleDbDataAdapter
Dim DSSet As New DataSet
SQLSet = "Select * From SetDisplayTable"
DASet = New OleDb.OleDbDataAdapter(SQLSet, Con)
DSSet.Clear()
DASet.Fill(DSSet, "DSSetHere")
With DGVSetView
.Refresh()
.AutoGenerateColumns = False
.DataSource = Nothing
.DataSource = DSSet.Tables(0)
.Update()
DGVSetView.Columns(i).DataPropertyName = DSSet.Tables(0).Columns(i).ToString
.Columns(0).DataPropertyName = DSSet.Tables(0).Columns(0).ToString
.Columns(2).DataPropertyName = DSSet.Tables(0).Columns(1).ToString
.Columns(3).DataPropertyName = DSSet.Tables(0).Columns(2).ToString
.Columns(4).DataPropertyName = DSSet.Tables(0).Columns(3).ToString
.Columns(5).DataPropertyName = DSSet.Tables(0).Columns(4).ToString
.Columns(6).DataPropertyName = DSSet.Tables(0).Columns(5).ToString
.Columns(7).DataPropertyName = DSSet.Tables(0).Columns(6).ToString
.Columns(8).DataPropertyName = DSSet.Tables(0).Columns(7).ToString
.Columns(9).DataPropertyName = DSSet.Tables(0).Columns(8).ToString
.Columns(10).DataPropertyName = DSSet.Tables(0).Columns(9).ToString
.Columns(11).DataPropertyName = DSSet.Tables(0).Columns(10).ToString 'Item Unique Code for Hot Edit
.Columns(14).DataPropertyName = DSSet.Tables(0).Columns(12).ToString
End With
'Updating Totals/::
For ItemRow As Integer = 0 To DGVSetView.Rows.Count - 1
If DGVSetView.Rows(ItemRow).Cells(14).Value = True Then
DGVSetView.Rows(ItemRow).Cells(12).Value = DGVSetView.Rows(ItemRow).Cells(10).Value
ElseIf DGVSetView.Rows(ItemRow).Cells(14).Value = False Then
DGVSetView.Rows(ItemRow).Cells(13).Value = DGVSetView.Rows(ItemRow).Cells(10).Value
End If
Next
'Updating School and general totals in DGV//:
Dim SchoolTotal, GeneralTotal As Decimal
For ColumnTotal As Integer = 0 To DGVSetView.Rows.Count - 1
SchoolTotal += DGVSetView.Rows(ColumnTotal).Cells(12).Value
GeneralTotal += DGVSetView.Rows(ColumnTotal).Cells(13).Value
Next
txtSchoolAmtFinal.Text = SchoolTotal
txtGeneralAmtFinal.Text = GeneralTotal
DGVSetView.Update()
'Get gross total of the DGV amount column//:
If DGVSetView.RowCount <> 0 Then
Dim GrossAmt As Decimal = 0
For Index As Integer = 0 To DGVSetView.RowCount - 1
' GrossAmt += Convert.ToDecimal(DataGridView1.Rows(Index).Cells(11).Value)
If Str(DGVSetView.Rows(Index).Cells(10).Value) = "Null" Or (DGVSetView.Rows(Index).Cells(10).Value) <= 0 Then
MsgBox("Item Number " & (DGVSetView.Rows(Index).Cells(10).Value) & " is either blank or 0", MsgBoxStyle.Exclamation, "Item Error")
Else
GrossAmt += Convert.ToDecimal(DGVSetView.Rows(Index).Cells(10).Value)
End If
Next
txtInsertGrossAmt.Text = GrossAmt ' - Val(DGVSetView.Text)
Call SetNetAmount()
End If
'Generate Serial//:
Dim X As Integer
Do While X < DGVSetView.Rows.Count
DGVSetView.Item(0, X).Value = X + 1
X = X + 1
Loop
'Disbaling editing in all columns except pending//:
With DGVSetView
.Columns(0).ReadOnly = True
.Columns(2).ReadOnly = True
.Columns(3).ReadOnly = True
.Columns(4).ReadOnly = True
.Columns(5).ReadOnly = True
.Columns(6).ReadOnly = True
.Columns(7).ReadOnly = True
.Columns(8).ReadOnly = True
.Columns(9).ReadOnly = True
.Columns(10).ReadOnly = True
End With
txtTotalItems.Text = DGVSetView.Rows.Count
For Each r As DataGridViewRow In DGVSetView.Rows
r.Cells(1).Value = True
Next r
End Sub
The problem is that occasionally,the DGV will not show any rows and displays a blank frame.At such instances.if I check in DGV.Rows.count
the result is 0 despite there being underlying data in the table.
Note that this happens randomly.At other times the DGV refreshed properly and also displays data correctly.
Also note that this DGV resides within a TabControl.
Further,when the DGV fails to display the data,the totals which I have calculated in the above sub procedure return zero value.As such the problem appears to lie somewhere in the rows not being inserted in the DGV.
Thank you.
Khalid.
//Edit;Code Updated:
#jmcilhinney I have updated my code as follows.However,the earlier problem of the DGV going blank occasionally persists.Also the update process has slowed down slightly.It seems I may be making a mistake in the location of placing the Suspend and ResumeBinding statements:
Private Sub SetPreview()
Dim SQLSet As String
Dim DASet As New OleDb.OleDbDataAdapter
Dim DSSet As New DataSet
SQLSet = "Select * From SetDisplayTable"
Dim DTDGV As New DataTable
Dim DGVBindingSource As New BindingSource
DASet = New OleDb.OleDbDataAdapter(SQLSet, Con)
DASet.Fill(DTDGV)
DGVBindingSource.DataSource = DTDGV
DGVBindingSource.ResumeBinding()
With DGVSetView
.AutoGenerateColumns = False
.DataSource = DGVBindingSource
.Columns(0).DataPropertyName = DTDGV.Columns(0).ToString
.Columns(2).DataPropertyName = DTDGV.Columns(1).ToString
.Columns(3).DataPropertyName = DTDGV.Columns(2).ToString
.Columns(4).DataPropertyName = DTDGV.Columns(3).ToString
.Columns(5).DataPropertyName = DTDGV.Columns(4).ToString
.Columns(6).DataPropertyName = DTDGV.Columns(5).ToString
.Columns(7).DataPropertyName = DTDGV.Columns(6).ToString
.Columns(8).DataPropertyName = DTDGV.Columns(7).ToString
.Columns(9).DataPropertyName = DTDGV.Columns(8).ToString
.Columns(10).DataPropertyName = DTDGV.Columns(9).ToString
.Columns(11).DataPropertyName = DTDGV.Columns(10).ToString 'Item Unique Code for Hot Edit
.Columns(14).DataPropertyName = DTDGV.Columns(12).ToString
End With
DGVBindingSource.SuspendBinding()
'Updating Totals/::
For ItemRow As Integer = 0 To DGVSetView.Rows.Count - 1
If DGVSetView.Rows(ItemRow).Cells(14).Value = True Then
DGVSetView.Rows(ItemRow).Cells(12).Value = DGVSetView.Rows(ItemRow).Cells(10).Value
ElseIf DGVSetView.Rows(ItemRow).Cells(14).Value = False Then
DGVSetView.Rows(ItemRow).Cells(13).Value = DGVSetView.Rows(ItemRow).Cells(10).Value
End If
Next
'Updating School and general totals in DGV//:
Dim SchoolTotal, GeneralTotal As Decimal
For ColumnTotal As Integer = 0 To DGVSetView.Rows.Count - 1
SchoolTotal += DGVSetView.Rows(ColumnTotal).Cells(12).Value
GeneralTotal += DGVSetView.Rows(ColumnTotal).Cells(13).Value
Next
txtSchoolAmtFinal.Text = SchoolTotal
txtGeneralAmtFinal.Text = GeneralTotal
DGVSetView.Update()
'Get gross total of the DGV amount column//:
If DGVSetView.RowCount <> 0 Then
Dim GrossAmt As Decimal = 0
For Index As Integer = 0 To DGVSetView.RowCount - 1
' GrossAmt += Convert.ToDecimal(DataGridView1.Rows(Index).Cells(11).Value)
If Str(DGVSetView.Rows(Index).Cells(10).Value) = "Null" Or (DGVSetView.Rows(Index).Cells(10).Value) <= 0 Then
MsgBox("Item Number " & (DGVSetView.Rows(Index).Cells(10).Value) & " is either blank or 0", MsgBoxStyle.Exclamation, "Item Error")
Else
GrossAmt += Convert.ToDecimal(DGVSetView.Rows(Index).Cells(10).Value)
End If
Next
txtInsertGrossAmt.Text = GrossAmt ' - Val(DGVSetView.Text)
Call SetNetAmount()
End If
'Disabling editing in all columns except pending//:
With DGVSetView
.Columns(0).ReadOnly = True
.Columns(2).ReadOnly = True
.Columns(3).ReadOnly = True
.Columns(4).ReadOnly = True
.Columns(5).ReadOnly = True
.Columns(6).ReadOnly = True
.Columns(7).ReadOnly = True
.Columns(8).ReadOnly = True
.Columns(9).ReadOnly = True
.Columns(10).ReadOnly = True
End With
txtTotalItems.Text = DGVSetView.Rows.Count
For Each r As DataGridViewRow In DGVSetView.Rows
r.Cells(1).Value = True
Next r
End Sub

Inserting to table in VB.NET, LINQ to SQL

This is the beginnings of a timetabling algorithm. The problem is with inserting a member into a group, but I have included the whole subroutine here for context. The table "membergroup" has 2 headings, MemberID and GroupID. No error code is thrown, but the table does not receive the new record.
I have gone through it line by line, and the values for iMember_Choice.MemberID and groupID_to_insert are correct.
Dim numberofrooms As Byte = rm.Count
Dim possiblerooms(numberofrooms + 1), possibleroomcounter As Int32
For TimeTableNumber = 1 To Val(NumberOfTimetablesToCreate.Text)
Dim memchoic = (dc.ExecuteQuery(Of memberChoice)("SELECT * FROM MemberChoices ORDER BY NEWID()")).ToList 'Orders list randomly
'sort into array for each rank, so highest ranks are allocated first
Dim Member_choices_Table_ordered_by_rank = From q In memchoic Order By q.Rank
For Each Member_Choice In Member_choices_Table_ordered_by_rank
ProgressBar.Value = ProgressBar.Value + 1
Dim iMember_Choice As memberChoice = Member_Choice
'Dim memactpossibleinstance(maxmemchoicernk, n) As memactvpossibleinstance
For Each room In rm
Dim rmid As Int32 = room.RoomID ' finds rooms activities can be in
If Not (From rom In roomact Where rom.ActivityID = iMember_Choice.ActivityID And rom.RoomID = rmid).FirstOrDefault Is Nothing Then 'finds suitable rooms
possiblerooms(possibleroomcounter) = rmid
possibleroomcounter = possibleroomcounter + 1
End If
Next
'find possible times
Dim roomid_to_insert, current_maximum_rank As Integer
Dim period_to_insert As String = "MonAM"
Dim staffact_that_can_do_this_activity = _
(From q In staffact Where q.ActivityID = iMember_Choice.ActivityID)
For roomcount = 0 To possibleroomcounter - 1 'for each room in roomcount, find rank for room
Dim rmid As Int32 = possiblerooms(roomcount)
For Each time In periods
Dim itime As String = time.Period
Dim Rank As Int16 = member_Error_check_period_count(iMember_Choice.MemberID, itime)
If Not (From rav In rmav Where rav.RoomID = rmid And rav.Period = itime) Is Nothing Then 'room is free
Rank = Rank + 12
Else ' room has an activity
Dim GroupID_now = (From q In instnce Where q.Period = itime And q.RoomID = rmid Select q.GroupID).SingleOrDefault
If GroupID_now <> 0 Then
Dim groupActID_now = (From q In grp Where q.GroupID = GroupID_now Select q.ActivityID).SingleOrDefault
'Dim activity_now = (From q In actv Where q.ActivityID = groupActID_now).SingleOrDefault
If groupActID_now = iMember_Choice.ActivityID Then 'Good, this activity is already on in this room
Rank = Rank + 50
If (From q In memgrp Where q.GroupID = GroupID_now).Count > 4 Then
Rank = Rank - 50
End If
End If
End If
End If
If Rank > current_maximum_rank Then
current_maximum_rank = Rank
roomid_to_insert = rmid
period_to_insert = itime
End If
Rank = 0
Next
possibleroomcounter = 0
Next 'for each room possible
Dim groupID_to_insert As Integer
If (From q In instnce Where q.Period = period_to_insert And q.RoomID = roomid_to_insert).FirstOrDefault Is Nothing Then
groupID_to_insert = insert_ins_group(period_to_insert, roomid_to_insert, iMember_Choice.ActivityID)
Else
groupID_to_insert = (From q In instnce Where q.Period = period_to_insert And q.RoomID = roomid_to_insert Select q.GroupID).SingleOrDefault
End If
'PROBLEM PROBPBLY HERE/////////////////////////////////////
memgrp.InsertOnSubmit(New membergroup With {.MemberID = iMember_Choice.MemberID, .GroupID = groupID_to_insert}) 'PROBLEM PROBABLY HERE
dc.SubmitChanges()
current_maximum_rank = 0
Next 'for each memberchoice
dc.SubmitChanges()
Next 'timetabl no
dc.SubmitChanges()
memgrp is initiated as
Dim memgrp As Table(Of membergroup) = dc.GetTable(Of membergroup)()

Multidimensional array problem

I want to create a multidimensional array with 2 columns and have the row size a dynamic value. I then want to populate the multidimensional array with values from 2 different SQL queries (Microsoft).
The problem is That when the page loads it seems to be empty. How can Fill each column with he two different recordsets?
Or
At least return the total number of rows in the recordset?
Code below -
connectionstring = obj_ADO.getconnectionstring
Set objCon = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.Recordset")
set objComm = CreateObject("ADODB.Command")
objCon.Open connectionstring
objComm.ActiveConnection = objCon.ConnectionString
objComm.CommandText = "A_Page_Paging"
objComm.CommandType = adCmdStoredProc
Set objParameter = objComm.CreateParameter
objParameter.Name = "selected_Char"
objParameter.Type = adChar
objParameter.Direction = adParamInput
objParameter.Size = 3
objParameter.Value = Selected_Button
objComm.Parameters.Append objParameter
set objRS = objComm.Execute
Increment = 0
Dim testArray()
while not objRS.EOF
Redim testArray(2, increment)
'--------------------------------------------
Page_ID = objRS("P_PageID")
connectionstring = obj_ADO.getconnectionstring
Set objConn = CreateObject("ADODB.Connection")
Set objRSS = CreateObject("ADODB.Recordset")
objConn.Open connectionstring
SQL = "Select P_Name as P_Name, P_Description as P_Description from L_PagePermission inner join A_Permission on p_permissionID = pp_PermissionID inner join A_Page on P_PageID = PP_PageID where P_PageID =" & Page_ID & " order by p_Name"
objRSS.open SQL, objConn
if not objRSS.EOF then
objRSS.MoveFirst
while not objRSS.EOF
'Fill Array
testArray(0, increment) = objRS("P_PageID")
objRSS.MoveNext
wend
objRSS.close
objConn.close
else
testArray(0, increment) = "-"
end if
Increment = Increment + 1
'--------------------------------------------
%>
<%
objRS.MoveNext
wend
objRS.Close
objCon.Close
response.Write testArray(0,5)
Figured it out myself by using preseve in the redim of my array so the code below fixed my problem -
'--------------------------------------------
Increment = 0
Dim testArray()
connectionstring = obj_ADO.getconnectionstring
Set objConn = CreateObject("ADODB.Connection")
Set objRSS = CreateObject("ADODB.Recordset")
objConn.Open connectionstring
SQL = "select * from a_permission inner join L_PagePermission on P_PermissionID = PP_PermissionID inner join A_Page on P_PageID = PP_PageID order by P_Name"
objRSS.open SQL, objConn
if not objRSS.EOF then
objRSS.MoveFirst
while not objRSS.EOF
Redim Preserve testArray(2, increment)
'Two Dimensional Array
testArray(0, increment) = objRSS("P_PageID")
testArray(1, increment) = objRSS("P_Name")
objRSS.MoveNext
Increment = Increment + 1
wend
objRSS.close
objConn.close
else
testArray(0, increment) = "-"
testArray(1, increment) = "-"
end if
'--------------------------------------------
'--------------------------------------------
Page_ID = objRS("P_PageID")
for i = 0 to (increment - 1)
if testArray(0, i) = Page_ID then
%>
<li style="" ="padding:0;margin:0;"><%=testArray(1,i)%></li>
<%
end if
next
'--------------------------------------------
If you run this query, do you get rows returned?
Select P_Name as P_Name, P_Description as P_Description from L_PagePermission inner join A_Permission on p_permissionID = pp_PermissionID inner join A_Page on P_PageID = PP_PageID where P_PageID =" & Page_ID & " order by p_Name

is there a way to do SELECT SCOPE_IDENTITY() in ADODB?

With rs
.AddNew ' create a new record
' add values to each field in the record
.Fields("datapath") = dpath
.Fields("analysistime") = atime
.Fields("reporttime") = rtime
.Fields("lastcalib") = lcalib
.Fields("analystname") = aname
.Fields("reportname") = rname
.Fields("batchstate") = bstate
.Fields("instrument") = instrument
.Update ' stores the new record
End With
this is how i am adding records. is it possibel to do something lik ethis???:
With rs
.AddNew ' create a new record
' add values to each field in the record
.Fields("datapath") = dpath
.Fields("analysistime") = atime
.Fields("reporttime") = rtime
.Fields("lastcalib") = lcalib
.Fields("analystname") = aname
.Fields("reportname") = rname
.Fields("batchstate") = bstate
.Fields("instrument") = instrument
SCOPE_IDENTITY() <----------------
.Update ' stores the new record
End With
No, there is not.
You should make an explicit INSERT statement followed by a call to SCOPE_IDENTITY in the same batch.
After you have executed the Update command, the identity will be placed in the corresponding field in the recordset. You can read it from there.
Example:
id = .Fields("id")

Automatic chart update with new data entry

My chart loads data from a DataGridView.
I want to automatically update my chart with new data if new values are inserted into the DataGridView.
My chart is bound to table1 and table2 in my DataGridView which gets values from a DataTable. Here is a small portion of the code:
Dim myData As New DataTable
wcAdapter.SelectCommand = wcCommand
wcAdapter.Fill(myData)
-
Chart1.DataSource = myData
Chart1.Series("Series1").ValueMemberX = "table1"
Chart1.Series("Series1").ValueMembersY = "table2"
Here is the complete code:
Try
wcconn.Open()
Dim wcCommand As New MySqlCommand()
''telesales name
' Dim wcQuery = "SELECT ID, Telesales, SUBSTRING(lastupdatedate, 1, 10) as 'Day', SUBSTRING(lastupdatetime FROM -9 FOR 6) as 'Time' FROM ratingout where Telesales='" & cbTelesales.Text & "' and lastupdatedate= '" & newDate & "' and lastupdatedate is not null and lastupdatetime is not null ORDER BY lastupdatetime ;"
' wcCommand.Connection = wcconn
' wcCommand.CommandText = wcQuery
Dim newDate As String
newDate = dateWorkCheck.Text
newDate = newDate.Replace("/", "-")
Dim y, m, d As String
y = newDate.Substring(6, 4)
m = newDate.Substring(3, 2)
d = newDate.Substring(0, 2)
newDate = y & "-" & m & "-" & d
Dim wcQuery = "SELECT ID, Telesales, lastupdatedate as 'Day', SUBSTRING(lastupdatetime FROM -8 FOR 2) as 'Time' FROM ratingout where Telesales='" & cbTelesales.Text & "' and lastupdatedate= '" & newDate & "' and lastupdatedate is not null and lastupdatetime is not null ORDER BY lastupdatetime ;"
wcCommand.Connection = wcconn
wcCommand.CommandText = wcQuery
Dim wcData As New DataTable
wcAdapter.SelectCommand = wcCommand
wcAdapter.Fill(wcData)
Dim i = 0
If wcData.Rows.Count = 0 Then
wcAdapter.Dispose()
Try
Dim wQuery = "SELECT ID, Telesales, lastupdatedate as 'Day', SUBSTRING(lastupdatetime FROM -8 FOR 2) as 'Time' FROM ratingout where Telesales='" & cbTelesales.Text & "' and lastupdatedate= '" & dateWorkCheck.Text & "' and lastupdatedate is not null and lastupdatetime is not null ORDER BY lastupdatetime ;"
wcCommand.Connection = wcconn
wcCommand.CommandText = wQuery
Dim wData As New DataTable
wcAdapter.SelectCommand = wcCommand
wcAdapter.Fill(wData)
wData.Columns.Add("tt")
wData.Columns.Add("num")
wcData.Columns.Add("tt")
wcData.Columns.Add("num")
'dgvWorkCheck.AutoSizeRowsMode = DataGridViewAutoSizeRowMode.AllCells
Dim dr As DataRow
For Each dr In wData.Rows
If lastV Is Nothing OrElse Not ColumnEqual(lastV, dr("Time")) Then
''check if first value is nothing
If lastV = Nothing Then
lastV = "00"
l = "0"
Else
dr("tt") = lastV
dr("num") = l
'wcData.Tables("ratingout").Rows(I)("ID") = dr("ID")
End If
ListBox1.Items.Add(lastV & " <--> " & l)
lastV = dr("Time")
l = 1
ElseIf lastV Is Nothing OrElse ColumnEqual(lastV, dr("Time")) Then
l += 1
'Dim series1 As New Series()
'series1.Points.Add(l)
End If
For I = I To wData.Rows.Count
If I <> wData.Rows.Count Then
I += 1
If i = wData.Rows.Count Then
dr("tt") = lastV
dr("num") = l
ListBox1.BeginUpdate()
ListBox1.Items.Add(dr("Telesales") & " between[" & lastV & " and 17:00, ] <--> " & l & "[ records ]")
ListBox1.EndUpdate()
End If
GoTo n
Else
MsgBox("last data")
End If
Next
n:
Next
txtRec.Text = wData.Rows.Count
dgvWorkCheck.DataSource = wData
''chart
Dim ChartArea2 As ChartArea = New ChartArea()
Dim Legend2 As Legend = New Legend()
Dim Series2 As Series = New Series()
Dim Chart2 = New Chart()
Me.Controls.Add(Chart2)
ChartArea2.AxisX.LabelStyle.Angle = -90
ChartArea2.AxisX.LabelStyle.Interval = 1
ChartArea2.AxisY.LabelStyle.Angle = -90
ChartArea2.AxisY.LabelStyle.Interval = 5
ChartArea2.Name = "ChartArea2"
Chart2.ChartAreas.Add(ChartArea2)
Legend2.Name = "Legend2"
Chart2.Legends.Add(Legend2)
Chart2.Location = New System.Drawing.Point(12, 113)
Chart2.Name = "Chart2"
Series2.ChartArea = "ChartArea2"
Series2.Legend = "Legend2"
Series2.Name = "Series2"
Chart2.Series.Add(Series2)
Chart2.Size = New System.Drawing.Size(1145, 604)
Chart2.TabIndex = 0
Chart2.Text = "Chart2"
Chart2.Series("Series2").XValueMember = "tt"
Chart2.Series("Series2").YValueMembers = "num"
Chart2.DataSource = dgvWorkCheck.DataSource
Chart2.DataBind()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Exit Try
since the new data is inserted into a database, you will only need to rebind the gridview to it's source in order to display the new incoming data.
You should isolate the code that binds data to your chart in a function and have it called every time a new field gets inserted:
Function FillChartWithData()
Dim myData As New DataTable
wcAdapter.SelectCommand = wcCommand
wcAdapter.Fill(myData)
...
Chart1.Series("Series1").ValueMemberX = "table1"
Chart1.Series("Series1").ValueMembersY = "table2"
End Function
EDIT
I looked at your coded and it seems you're missing the part responsible for inserting new data inside the 'ratingout' table. You should create a function that allows you to insert new data, something along the line of:
Dim insertRating = "INSERT INTO ratingout VALUES (#NewTeleSalesName, #NewDate);"
Dim insertCmd As New MySqlCommand(insertRating, wcconn)
insertCmd.Parameters.Add("#NewTeleSalesName", MySqlDbType.VarChar, 255, "teleSalesName")
insertCmd.Parameters.Add("#NewDate", MySqlDbType.Datetime, 8, New DateTime(2010, 8, 5))
insertCmd.ExecuteNonQuery()
In order to update my chart bargraph named CashChart (which was databound to a BindingSource) I had to do the following:
To clear the chart information,
Clear the bounding source information
And then re-assign the bounding source information: for example:
CashChart.Series(0).Points.Clear()
CashChart.DataSource = ""
CashChart.DataSource = ESTADOINSTANTANEOBindingSource
Before, only my DataTable was updating, but after these commands, I was able to get the bargraph to update with new values in the table.