How to make function work together with Control.CheckForIllegalCrossThreadCalls - vb.net

When I comment Control.CheckForIllegalCrossThreadCalls = False my function works fine but when uncommented it gives an error
I am using a BackgroundWorker to call a function that inserts values into the database and there is a requirement for me to set Control.CheckForIllegalCrossThreadCalls = False in order for the code to work properly. Now when I set it to false one of the functions does not work as expected. Here is the error
Conversion from string "-0-1-22" to type 'Date' is not valid"
yet when that function works fine
Private Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
If Not BackgroundWorker1.IsBusy = True Then
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
I expect the function to come up with "2019-06-11" as date to be inserted to the database of which works fine without Control.CheckForIllegalCrossThreadCalls = False
Here is the code
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
count_rows()
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("Products imported successfully!", MsgBoxStyle.Information, "Import")
Me.Close()
End Sub
Public Sub count_rows()
import_attendance_sheet(1054)
End Sub
Private Sub import_attendance_sheet(ByVal id As Integer)
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = id
ProgressBar1.Value = 0
Dim path As String = txtPath.Text
Dim excel_connection As OleDbConnection
Dim dt As DataTable
Dim cmd As OleDbDataAdapter
'Dim sql As String
'Dim result As Boolean
Dim emp_type_id As String = ""
Dim branch_id As String = ""
Dim bank_id As String = ""
'Dim sheet_dates As New List(Of String)
'excel_connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + path + ";Extended Properties=Excel 12.0 Xml; HDR=Yes;")
excel_connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0 Xml;HDR=No;IMEX=1;';")
cmd = New OleDbDataAdapter("SELECT * FROM [sheet$]", excel_connection)
dt = New DataTable
cmd.Fill(dt)
'initialize symbol row
Dim count As Integer = 6
'Loop through dates(column/header)
For Each column As DataColumn In dt.Columns
Dim colum_name As String = dt.Rows(0)(column.ColumnName).ToString()
'check if column cell is empty
If colum_name = "" Then
'Empty do nothing
Else
'increment symbol row by 1
count = count + 1
'MsgBox(count)
'Loop through rows of a particular date/column/header
For Each r As DataRow In dt.Rows
'check row(empNo) cell is not empty & does not have a string
If r(5).ToString() = "" Or r(5).ToString() = "COY #" Then
'Empty do nothing
Else
'show date | Emp No | Name | symbol index
'MsgBox(colum_name & " " & r(5).ToString() & " " & r(6).ToString() & " " & r(count).ToString())
'do the calculation
Dim employ_id As String = get_employee_id(r(5).ToString)
Dim basic_salary As Decimal = get_employee_basic_salary(r(5).ToString)
Dim staff_type_id As String = get_employee_type_id(r(5).ToString)
Dim days_per_month As Integer = get_employee_days_per_month(staff_type_id)
Dim hours_per_day As Double = get_employee_hours_per_day(staff_type_id)
Dim hourly_rate As Double = basic_salary / days_per_month / hours_per_day
Dim daily_rate As Double = basic_salary / days_per_month
Dim normal_working_hrs As String = get_normal_working_hrs()
Dim shift_duration As String = get_shift_duration()
'get symbol id and its rate
Dim symbol_id As String = get_attendance_symbol_id(r(count).ToString)
Dim symbol_rate As Double = get_attendance_symbol_rate(symbol_id)
Dim symbol_deduction_status As String = get_symbol_deduction_status(symbol_id)
Dim td_amount As Double = 0
If symbol_deduction_status = "DEDUCT" Then
td_amount = hourly_rate
Else
td_amount = 0
End If
Dim overtime As Double = shift_duration - normal_working_hrs
Dim ot_amount As Double = overtime * hourly_rate * symbol_rate
Dim chaka As String = Date.Now.ToString("yyyy")
Dim tsiku As String = Date.Now.ToString("dd")
Dim tsiku_mawu As String = Date.Now.ToString("dddd")
Dim mwezi As String = Date.Now.ToString("MMMM")
' ''insert values into DB
Sql = "INSERT INTO tbl_attendance (employee_id,time_in,time_out,total_hours_worked,overtime,ot_amount,td_amount,attendance_code_id,attendance_code,attendance_date,comment,year,date,day,month,hourly_rate,bsalary,ot_status) VALUES ('" & employ_id & "','" & 0 & "','" & 0 & "','" & shift_duration & "','" & overtime & "','" & ot_amount & "','" & td_amount & "','" & symbol_id & "','" & r(count).ToString & "','" & calc_attendance_date(colum_name) & "','import','" & chaka & "','" & tsiku & "','" & tsiku_mawu & "','" & mwezi & "','" & hourly_rate & "','" & basic_salary & "','" & symbol_rate & "')"
result = save_to_db(Sql)
ProgressBar1.Value = ProgressBar1.Value + 1
'If result Then
' Timer1.Start()
'End If
End If
Next
End If
Next
End Sub
'******* Function which shows the error ****************
Public Function calc_attendance_date(ByVal value As String)
Dim at_date As String = ""
Dim current_month As String = frmMain.cmbMonth.Text
Dim current_year As String = frmMain.cmbYear.Text
Dim mwezi As String
Dim chaka As String
Dim format_day As String = ""
Dim format_month As String = ""
'Date.Now.ToString("yyyy-MM-dd")
'**** find previous month
'when its january
If current_month = "January" And value >= 22 And value <= 31 Then
mwezi = "12"
chaka = Convert.ToInt32(current_year) - 1
at_date = chaka & "-" & mwezi & "-" & value
ElseIf current_month <> "January" And value >= 22 And value <= 31 Then
mwezi = IntMonth() - 1
'day
If value < 10 Then
format_day = "0" & value
ElseIf value >= 10 Then
format_day = value
End If
'format mwezi
If mwezi < 10 Then
format_month = "0" & mwezi
ElseIf mwezi >= 10 Then
format_month = mwezi
End If
chaka = current_year
at_date = chaka & "-" & format_month & "-" & format_day
End If
'**** find current month
If current_month = "January" And value >= 1 And value <= 21 Then
mwezi = IntMonth()
chaka = current_year
'day
If value < 10 Then
format_day = "0" & value
ElseIf value >= 10 Then
format_day = value
End If
'format mwezi
If mwezi < 10 Then
format_month = "0" & mwezi
ElseIf mwezi >= 10 Then
format_month = mwezi
End If
at_date = chaka & "-" & format_month & "-" & format_day
ElseIf current_month <> "January" And value >= 1 And value <= 21 Then
mwezi = IntMonth()
chaka = current_year
'day
If value < 10 Then
format_day = "0" & value
ElseIf value >= 10 Then
format_day = value
End If
'format mwezi
If mwezi < 10 Then
format_month = "0" & mwezi
ElseIf mwezi >= 10 Then
format_month = mwezi
End If
at_date = chaka & "-" & format_month & "-" & format_day
End If
Return at_date
End Function

You shouldn't try to interact with UI controls from a non-UI thread. You can however have code which interacts with those controls on a UI thread by using Control.Invoke. There are a few places where you do it.
Inside import_attendance_sheet
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = id
ProgressBar1.Value = 0
Dim path As String = txtPath.Text
...
ProgressBar1.Value = ProgressBar1.Value + 1
Instead:
Dim path As String
Me.Invoke(
Sub()
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = id
ProgressBar1.Value = 0
path = txtPath.Text
End Sub)
...
Me.Invoke(Sub() ProgressBar1.Value += 1)
All those functions like get_employee_id, get_employee_basic_salary, get_employee_type_id may also interact with the UI, but you don't provide them. If they do (i.e. return a value from a textbox or something) then you need to invoke inside them as well.
Inside calc_attendance_date
Dim current_month As String = frmMain.cmbMonth.Text
Dim current_year As String = frmMain.cmbYear.Text
Instead:
Dim current_month As String
Dim current_year As String
Me.Invoke(
Sub()
current_month = frmMain.cmbMonth.Text
current_year = frmMain.cmbYear.Text
End Sub)
The function IntMonth() is unknown to us too. Again, if it reads from the UI you should invoke the code which does the UI interaction.
The correct way to do this is only invoke when absolutely necessary, i.e. when Control.InvokeRequired. See this example which is very close to yours in that they wanted to use Me.CheckForIllegalCrossThreadCalls = False (BAD!)
Even better, you can write extension methods to automate the Control.InvokeRequired pattern

Related

Why is my Sub printing only 1 line at a time instead of 30?

I'm currently writing a GUI for xmr-stak (www.xmrgui.com)
Having some trouble getting the output from the program and basically want to grab the last 30 lines from the output text file and append them to the RichTextBox if they don't already exist. Storing the text file in memory isn't a big issue because it will be deleted every 20 min or so...at least so I think. Maybe my function is taking up too much memory or time as it is.
My only requirement is that the Sub TimerOutput_tick can process each of the 30 last lines of text from the file to run a regex on each line and that the RichTextBox does not repeat old information.
Heres my code:
Private Function getlastlines(filename As String, numberOfLines As Integer) As Dictionary(Of Integer, String)
Try
Dim fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim reader As StreamReader = New StreamReader(fs)
Dim everything As New Dictionary(Of Integer, String)
Dim n As Integer = 1
While reader.Peek > -1
Dim line = reader.ReadLine()
If everything.ContainsKey(n) Then
everything(n) = line
n += 1
Else
everything.Add(n, line)
n += 1
End If
End While
Dim results As New Dictionary(Of Integer, String)
Dim z As Integer = 1
If n - numberOfLines > 0 Then
For x As Integer = n - numberOfLines To n - 1
'MsgBox(everything.Count - numberOfLines)
If results.ContainsKey(z) Then
results(z) = everything(x)
z += 1
Else
results.Add(z, everything(x))
z += 1
End If
Next
End If
Return results
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Function
' GRABS XMR-STAK OUTPUT FROM ReadLastLinesFromFile AND RUNS A REGEX ON THE HASHRATE TO PROVIDE VALUES TO THE CHART
And here is the Sub that calls the previous function:
Private Sub timeroutput_Tick(sender As Object, e As EventArgs) Handles timeroutput.Tick
'Try
Dim lateststring = getlastlines(xmroutput, 30)
Try
If lateststring IsNot rtlateststring Then
Dim kvp As KeyValuePair(Of Integer, String)
For Each kvp In lateststring
If lateststring.ContainsKey(kvp.Key) Then
Dim line = kvp.Value
RichTextBox1.AppendText(line & vbCrLf)
If line.Contains("Totals") Then ' Should be "Totals"
'Dim regex As Regex = New Regex("\d+?.\d+")
Dim regex As Regex = New Regex("\d{1,5}\.\d{1,1}") ' match a double
Dim ret = regex.Match(line).Value
If ret <> "" Then
Dim iSpan As TimeSpan = TimeSpan.FromSeconds(upseconds)
Label8.Text = "Uptime - Hours: " & iSpan.Hours & " Minutes: " & iSpan.Minutes & " Seconds: " & iSpan.Seconds & " " & ret & " H/s"
NotifyIcon1.Text = "Uptime - Hours: " & iSpan.Hours & vbCrLf & " Minutes: " & iSpan.Minutes & vbCrLf & " Seconds: " & iSpan.Seconds & vbCrLf & ret & " H/s"
Else
Dim iSpan As TimeSpan = TimeSpan.FromSeconds(upseconds)
NotifyIcon1.Text = "Uptime - Hours: " & iSpan.Hours & vbCrLf & " Minutes: " & iSpan.Minutes & vbCrLf & " Seconds: " & iSpan.Seconds & vbCrLf & "Initializing..."
Label8.Text = "Uptime - Hours: " & iSpan.Hours & " Minutes: " & iSpan.Minutes & " Seconds: " & iSpan.Seconds & " Initializing..."
ret = "0.0"
End If
'Dim match As Match = regex.Match(lastline)
newhashrate = Convert.ToDouble(ret)
ElseIf line.Contains("NVIDIA") Then
Dim regexnv As Regex = New Regex("\d{1,5}\.\d{1,1}") ' match a double
Dim retnv = regexnv.Match(line).Value
newNVhashRate = Convert.ToDouble(retnv)
If firstNV = False Then
newser.Add(nvidiacard1)
nvidiacard1.Title = "NIVIDIA Hashrate(H/s)"
nvidiacard1.Values = nvidiavalues
nvidiavalues.add(0)
nvidiavalues.add(4)
nvidiavalues.add(2)
nvidiavalues.add(5)
firstNV = True
End If
ElseIf line.Contains("AMD") Then
Dim regexAMD As Regex = New Regex("\d{1,5}\.\d{1,1}") ' match a double
Dim retAMD = regexAMD.Match(line).Value
newAMDhashrate = Convert.ToDouble(retAMD)
If firstAMD = False Then
newser.Add(AMDCard1)
AMDCard1.Title = "AMD Hashrate(H/s)"
AMDCard1.Values = AMDValues
AMDValues.add(0)
AMDValues.add(4)
AMDValues.add(2)
AMDValues.add(5)
firstAMD = True
End If
End If
' Now if a GPU exists, add a new lineseries for CPU
If firstAMD = True Or firstNV = True Then
If firstCPU = False Then
newser.Add(CPU1)
CPU1.Title = "CPU Hashrate(H/s)"
CPU1.Values = CPUValues
CPUValues.add(0)
CPUValues.add(4)
CPUValues.add(2)
CPUValues.add(5)
firstCPU = True
End If
newCPUhashrate = newhashrate - newNVhashRate - newAMDhashrate
End If
rtlateststring = lateststring
End If
Next
RichTextBox1.SelectionStart = RichTextBox1.Text.Length
End If
Catch
End Try
End Sub
I've found a much easier solution, running the code within one function and then loading the entire text file into the richtextbox. From there its much easier to read the last ten lines individually:
Private Sub timeroutput_Tick(sender As Object, e As EventArgs) Handles timeroutput.Tick
Try
'Dim lateststring = getlastlines(xmroutput, 30)
' START NEW TEST
Dim fs = File.Open(xmroutput, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim reader As StreamReader = New StreamReader(fs)
Dim wholefile = reader.ReadToEnd
RichTextBox1.Text = wholefile
RichTextBox1.SelectionStart = RichTextBox1.Text.Length
For x As Integer = 1 To 10
Dim line As String = RichTextBox1.Lines(RichTextBox1.Lines.Length - x)
If line.Contains("Totals") Then ' Should be "Totals"
'Dim regex As Regex = New Regex("\d+?.\d+")
Dim regex As Regex = New Regex("\d{1,5}\.\d{1,1}") ' match a double
Dim ret = regex.Match(line).Value
If ret <> "" Then
Dim iSpan As TimeSpan = TimeSpan.FromSeconds(upseconds)
Label8.Text = "Uptime - Hours: " & iSpan.Hours & " Minutes: " & iSpan.Minutes & " Seconds: " & iSpan.Seconds & " " & ret & " H/s"
NotifyIcon1.Text = "Uptime - Hours: " & iSpan.Hours & vbCrLf & " Minutes: " & iSpan.Minutes & vbCrLf & " Seconds: " & iSpan.Seconds & vbCrLf & ret & " H/s"
Else
Dim iSpan As TimeSpan = TimeSpan.FromSeconds(upseconds)
NotifyIcon1.Text = "Uptime - Hours: " & iSpan.Hours & vbCrLf & " Minutes: " & iSpan.Minutes & vbCrLf & " Seconds: " & iSpan.Seconds & vbCrLf & "Initializing..."
Label8.Text = "Uptime - Hours: " & iSpan.Hours & " Minutes: " & iSpan.Minutes & " Seconds: " & iSpan.Seconds & " Initializing..."
ret = "0.0"
End If
'Dim match As Match = regex.Match(lastline)
newhashrate = Convert.ToDouble(ret)
ElseIf line.Contains("NVIDIA") Then
Dim regexnv As Regex = New Regex("\d{1,5}\.\d{1,1}") ' match a double
Dim retnv = regexnv.Match(line).Value
newNVhashRate = Convert.ToDouble(retnv)
If firstNV = False Then
newser.Add(nvidiacard1)
nvidiacard1.Title = "NIVIDIA Hashrate(H/s)"
nvidiacard1.Values = nvidiavalues
For Each z In Chartvalues
Chartvalues.remove(z)
Next
nvidiavalues.add(0)
firstNV = True
End If
ElseIf line.Contains("AMD") Then
Dim regexAMD As Regex = New Regex("\d{1,5}\.\d{1,1}") ' match a double
Dim retAMD = regexAMD.Match(line).Value
newAMDhashrate = Convert.ToDouble(retAMD)
If firstAMD = False Then
newser.Add(AMDCard1)
AMDCard1.Title = "AMD Hashrate(H/s)"
AMDCard1.Values = AMDValues
For Each z In Chartvalues
Chartvalues.remove(z)
Next
AMDValues.add(0)
firstAMD = True
End If
End If
' Now if a GPU exists, add a new lineseries for CPU
If firstAMD = True Or firstNV = True Then
If firstCPU = False Then
newser.Add(CPU1)
CPU1.Title = "CPU Hashrate(H/s)"
CPU1.Values = CPUValues
For Each z In Chartvalues
Chartvalues.remove(z)
Next
CPUValues.add(0)
Chartvalues.add(0)
firstCPU = True
End If
newCPUhashrate = newhashrate - newNVhashRate - newAMDhashrate
End If
Next
Catch
End Try
' END NEW TEST
End Sub

Unable to add records more than 28 in access database

I am making my first project using vb.net and access. I am trying to develop a project in which the data of patients of the is added from different counters.it works fine till 22nd or 23rd record entered. after that adding new record over writes the last saved record.
to check the database i deleted some record (say after deletion there are 13 records left in the database) and tried to add new record, it gives the same problem, the 13th record is overwritten by the new record.
i deleted all the records and tried to add new record, the first record successfully entered but after that new record entry over writes the last (only) record.
i'm unable to understand the problem
code for saving data is
Private Sub Save()
'Dim st As String
Dim str As String
btnSave_Click = False
str = check
If Not str = "" Then
MsgBox(str, vbInformation, "Patient Registration")
btnSave_Click = False
Exit Sub
End If
If conn.State = 0 Then
Module1.openConnection()
End If
If Not rsDept Is Nothing Then
If rsDept.State = 0 Then
Call openRecordset("SELECT * FROM tblDept", rsDept)
End If
Else
Call openRecordset("SELECT * FROM tblDept", rsDept)
End If
If Not rsData Is Nothing Then
If rsData.State = 0 Then
Call openRecordset("Select * from tblPatientRecord", rsData)
End If
Else
Call openRecordset("Select * from tblPatientRecord", rsData)
End If
conn.BeginTrans()
On Error GoTo ProcError
If Not (rsData.BOF And rsData.EOF) Then
rsData.MoveLast()
Call addData(rsData)
Else
Call addData(rsData)
End If
conn.CommitTrans()
MsgBox("Patient's Record Saved Successfully...!", MsgBoxStyle.Information, "Patient Registration")
Call loadDataListview()
Call fieldDisable()
Call Disable_SearchButtons()
btnSave_Click = True
comDepart.Enabled = False
conn.Close()
ProcError:
If Err.Number <> 0 Then
conn.RollbackTrans()
MsgBox(Err.Number & " " & Err.Description)
Call addNewR()
Exit Sub
End If
End Sub
Private Sub addData(rData As ADODB.Recordset)
Dim rsPaymentType As New ADODB.Recordset
'Dim str As String
If Not (rData.BOF And rsData.EOF) Then
rData.MoveFirst()
If rData.RecordCount > 0 Then
Do
If txthn.Text = rData("hNumber").Value Then
Call addVisit()
conn.Execute("update tblPatientRecord set visitNo = '" & vNo.Text & "' where hNumber = '" & txthn.Text & "'")
Call fieldEnable()
Exit Sub
End If
rData.MoveNext()
Loop Until rData.EOF
End If
End If
rData.AddNew()
rData("hNumber").Value = txthn.Text
rData("fName").Value = txtfn.Text
rData("contactNo").Value = txtContact.Text
rData("address").Value = txtaddress.Text
rData("cnic").Value = txtcnic.Text
'rData("cnic").Value = rCNIC()
rsData("visitNo").Value = vNo.Text
rsData("cnicSD").Value = comSD.Text
''Add gender as selected
If radmale.Checked = True Then
rData("gender").Value = radmale.Text
ElseIf radfemale.Checked = True Then
rData("gender").Value = radfemale.Text
Else
rData("gender").Value = " - "
End If
If txtAge.Text < 105 Or Year(dtAgePicker.Value) < 1915 Then
Call addAge()
'MsgBox("data of tblAge added")
Else
MsgBox("Please Enter Correct Age ", vbCritical, "")
txtAge.Select()
Exit Sub
End If
If comRelation.Text = "Select Relation with Patient" Or comRelation.Text = "" Then
comRelation.Text = "Not Selected"
End If
If txtfh.Text = "" Then
txtfh.Text = "Not Given"
End If
Call addRelation()
'Save Department ID as selected
If comDepart.Text <> "Select Department" Then
Call addVisit()
'MsgBox("data of tblVisit added")
Else
MsgBox("Please Enter the Department ", vbCritical, "")
comDepart.Select()
Exit Sub
End If
If Not rsPaymentType Is Nothing Then
If rsPaymentType.State = 0 Then
Call openRecordset("Select * from tblPaymentType", rsPaymentType)
'MsgBox("Patient record is open" & rsData.State)
End If
Else
Call openRecordset("Select * from tblPaymentType", rsPaymentType)
'MsgBox("Patient record is open")
End If
If Not (rsPaymentType.BOF And rsPaymentType.EOF) Then
rsPaymentType.MoveFirst()
Do
If rsPaymentType("paymentType").Value = comPaymentType.Text Then
rData("paymentType").Value = rsPaymentType("paymentTypeID").Value
Exit Do
Else
rData("paymentType").Value = 0
End If
rsPaymentType.MoveNext()
Loop Until rsPaymentType.EOF
End If
rsData.Update()
End Sub
Public Function h_N0_Generator(rs As ADODB.Recordset) As String
Dim str, p1() As String
Dim auto_long As Long
Dim hMonth As String
Dim strCounter As String, temp As String
'this counter file is added to make the hNumber unique for multiple counter /* in the file counter number is added and have respective counter number only*/
FileOpen(FileNum, "C048ounter.txt", OpenMode.Input)
strCounter = LineInput(FileNum)
FileClose(FileNum)
If strCounter = "" Then
strCounter = "1"
End If
hMonth = Month(Now).ToString("D2")
If (rs.EOF And rs.BOF) Then
h_N0_Generator = "NIRM-" & Year(Now) & "-" & hMonth & "-" & "00000" & strCounter
Else
rs.MoveLast()
str = rs("HNumber").Value
p1 = str.Split("-")
' check if the current month is the same as in last stored Hospital No or not
'if yes the last five digits increment otherwise it restarts with 0
If p1(2) = Month(Now) And p1(1) = Year(Now) Then
temp = Right(rs(0).Value, 6)
auto_long = Left(temp, 5) + 1
h_N0_Generator = "NIRM-" & Year(Now) & "-" & hMonth & "-" & Right("00000" & auto_long, 5) & strCounter
Else
h_N0_Generator = "NIRM-" & Year(Now) & "-" & hMonth & "-" & "00000" & strCounter
End If
End If
'Return auto_num
End Function

Batching results SQL Server 2008 R2

How would I go about batching records in a select statement I Have to conserve bandwidth as delaying with shop tills so bandwidth is at a premium. I will be reading the batch size from configuration file and passing to this select statement:
Friend Function SelectAllPendingDeliveries() As String Implements iScriptBuilder.SelectAllPendingDeliveries
Dim retVal As String = ""
retVal = "Select * from batchtable where [location] is not null and isprocessed = 0"
Return retVal
End Function
How would I go about doing this is the table structure
#Anthoy I think this is where I am getting tripped up how Would i control it here to for it to loop until the end of the recordset so it executes in batches this is the function that calls the select statement
#Anthory I meen this code i pasted the wrong proc in
Friend Function CreateLiveSale(ByVal wrpPush As LiveSales.wrpPush, ByVal rCount As Int32, ByVal request As LiveSales.requestPush, ByVal orderLineData As DataTable, ByVal packetBatchSize As String) ', ByVal orderNumber As String, ByVal orderLineReference As String, ByVal uniqueFilename As String, ByVal tagBarCode As String, ByVal costPrice As String, ByVal deliveryQty As Int32, ByVal orderLineData As DataTable) As Boolean
Dim retVal As Boolean
Dim settings As LiveSalesBackOfficeClient.infoLiveSalesBackOfficeClient = _
(New LiveSalesBackOfficeClient.configurationLoader).LoadConfiguration
Dim cfb As New cfbConfiguration
Dim pushOrderIncQTY As New infoPushOrderIncQTY()
Dim totalRecords As Integer = orderLineData.Rows.Count
Dim pushOrderInc As List(Of infoPushOrderIncQTY) = New List(Of infoPushOrderIncQTY)() ' create a generic list
Dim recordCount As Integer = 0
Dim batchNumber As Integer
Dim batchNumberpad As String
Dim filenameSplit As String()
For Each thisentry In orderLineData.Rows
If recordCount = 0 Then
filenameSplit = thisentry.Item("unqiueFilename").ToString().Split("_")
batchNumber = recordCount + 1
batchNumberpad = Path.GetFileNameWithoutExtension(filenameSplit(2)) & "_" & batchNumber.ToString("D3") & ".csv"
With request
.companyID = settings.companyID
.machineID = settings.machineID
.uniqueBatchIdentifier = batchNumberpad
End With
End If
With pushOrderIncQTY
.costPrice = thisentry.Item("costPrice")
.externalTimeStamp = DateTime.Now()
.RootPLU = thisentry.Item("tagbarcode") 'set this to the barcode from the file
.sizeBit = -666
.supplierID = cfb.SupplierID
.orderReference = thisentry.Item("OrderNumber")
.orderLineReference = ""
.externalTransaction = ""
.sourceShop = cfb.SiteId 'set to the GEMINI location ID for this store (you will have to get this from your configuration file
.destinationShop = cfb.SiteId 'set this to the same as the sourceshop
.QTY = thisentry.Item("ActQty")
.whichQty = LiveSales.infoPushOrderIncQTY.Which_OrderQty.delivered 'only available option at present
End With
recordCount = recordCount + 1
pushOrderInc.Add(pushOrderIncQTY) ' add it to the list for batching
If recordCount = cfb.PacketBatchSize Then ' only when the record count = the packetsize fire off
pushOrderInc.Clear()
recordCount = 0
End If
If cfb.PacketBatchSize > 0 Then
CallWebSerivce(wrpPush, request, pushOrderInc.ToArray())
End If
Next
If cfb.PacketBatchSize = 0 Then ' if their is a batch size then lets just processe
'call the webservice
CallWebSerivce(wrpPush, request, pushOrderInc.ToArray())
End If
Return retVal
End Function
#anthoy the above gets called by this procedure so it does its hear the looping needs to happen
OpenConnection()
Dim results As DataTable = connection.SqlSelectToDataTable(scriptBuilder.SelectAllPendingDeliveries)
Dim dataForEmail As String = ""
Dim msg As String = ""
msg = "The Following Deliverys where processed for the Following Ordernumbers at " & DateTime.Now.ToString() & Chr(13)
dataForEmail = "Order Number" & vbTab & "BarCode" & vbTab & vbTab & vbTab & "Product Name" & vbTab & vbTab & vbTab & vbTab & vbTab & "Brand" & vbTab & vbTab & vbTab & "Size" & vbTab & vbTab & "Colour" & vbTab & "Qty" & vbTab & vbTab & "RRP" & vbTab & Chr(13)
Dim totalcost As Decimal
Dim cnt As Int16 = 0
Dim fileName As String = ""
If Not IsNothing(results) AndAlso Not IsNothing(results.Rows) _
AndAlso results.Rows.Count > 0 Then
Dim rrpprice As Double = 0.0
For Each thisRow As DataRow In results.Rows
If IsDBNull(thisRow.Item("RRPPrice")) Then
rrpprice = 0.0
Else
rrpprice = thisRow.Item("RRPPrice")
End If
fileName = thisRow.Item("unqiueFilename")
totalcost = totalcost + rrpprice * thisRow.Item("QTY")
dataForEmail = dataForEmail & BuildReportFoEmail(thisRow)
connection.ExecuteNonQuerySql(scriptBuilder.SetDeliveryStatus(2, 1, thisRow.Item("r3DeliveryId")))
cnt = cnt + 1
Next
connection.ExecuteNonQuerySql(scriptBuilder.SetDeliveryStatus(1, 0))
CreateLiveSalesDeliveryForR3(cnt, fileName, results, cfb.PacketBatchSize)
dataForEmail = dataForEmail & vbCrLf & "Total Price " & totalcost.ToString() & vbCrLf & BuildExceptionsForEmail(results) & vbCrLf
End If
SendEmailViaWebService(dataForEmail, cfb.EmailForDeliverys, cfb.FullNameForEmailSubject, msg)
MsgBox("Delvery Complete", vbInformation, "Delivery Import")
CloseConnection()

Search between two dates w/ datarows in vb 2010

I am trying to search between two dates in a bound source (SQL table) in VB 2010, using data rows. Since 'between' in unsupported with the data rows function, I used < and >.
So I run this code and the output is 900+ entries when the actual number of entries is 8. After hitting my button a second time without changing anything, the correct number of entries appears.
Private Sub cmdSearch_Click(sender As System.Object, e As System.EventArgs) _
Handles cmdSearch.Click
Dim Expression As String
Dim OrderStr As String = "Area"
Dim DateStr As String
Dim StartDate As String
Dim EndDate As String
Dim Shift As String = ""
Dim Area As String = ""
Dim Product As String
If (DtpStartDate.Value = Nothing Or DtpEndDate.Value = Nothing) Then
MsgBox("Please input a start and end date.")
Exit Sub
End If
If (radShiftAllSearch.Checked <> True _
And radShiftOneSearch.Checked <> True
And radShiftTwoSearch.Checked <> True _
And radShiftThreeSearch.Checked <> True) Then
MsgBox("Please select a shift to search for.")
Exit Sub
End If
Select Case True
Case radShiftOneSearch.Checked
Shift = " AND [Shift] = '1'"
Case radShiftTwoSearch.Checked
Shift = " AND [Shift] = '2'"
Case radShiftThreeSearch.Checked
Shift = " AND [Shift] = '3'"
Case radShiftAllSearch.Checked
Shift = " AND ([Shift] = '1' OR [Shift] = '2' OR [Shift] = '3')"
End Select
**StartDate = DtpStartDate.Value.Subtract(oneday)
EndDate = DtpEndDate.Value.Add(oneday)
'StartDate = Format(DtpStartDate.Value.Subtract(oneday), "M/dd/yyyy")
'EndDate = Format(DtpEndDate.Value.Add(oneday), "M/dd/yyyy")
DateStr = "[Dates] > '" & StartDate & "' AND [Dates] < '" & EndDate & "'"**
If (txtProductSearch.Text = "") Then
Product = ""
Else
Product = "AND [Product] LIKE '" & txtProductSearch.Text & "'"
End If
For h As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Dim XDRV As DataRowView = CType(CheckedListBox1.CheckedItems(h), DataRowView)
Dim XDR As DataRow = XDRV.Row
Dim XDisplayMember As String = XDR(CheckedListBox1.DisplayMember).ToString()
If (Area = "") Then
Area = Area & " AND ([Area] LIKE '" & XDisplayMember & "'"
Else
Area = Area & " OR [Area] LIKE '" & XDisplayMember & "'"
End If
Next
If (Area <> "") Then
Area = Area & ")"
End If
Expression = DateStr & Product & Shift & Area
TextBox4.Text = Expression
Dim SearchRows() As DataRow = _
ProductionDataSet.Tables("Production_Daily").Select(Expression, OrderStr)
'foundcount = SearchRows.Count - 1
DataGridView1.DataSource = SearchRows
DataGridView1.Show()
End Sub
Thanks

vbnet multiple combobox fill with one dataset

i have the following code to fill two comboboxes using one dataset:
Private Sub sub_cbo_type_load()
Dim ds As New DataSet
ds = cls.cbo_type()
If ds IsNot Nothing _
AndAlso ds.Tables.Count > 0 _
AndAlso ds.Tables(0).Rows.Count > 0 Then
Me.r_cbo_type.DataSource = ds.Tables(0)
Me.r_cbo_type.DisplayMember = "desc"
Me.r_cbo_type.ValueMember = "code"
Me.r_cbo_type.SelectedIndex = -1
Me.m_cbo_type.DataSource = ds.Tables(0)
Me.m_cbo_type.DisplayMember = "desc"
Me.m_cbo_type.ValueMember = "code"
Me.m_cbo_type.SelectedIndex = -1
End If
End Sub
the problems is: whenever the index is changed in one combobox, it's automatically changed in the other one too.
does anyone know how can i solve this?
thanks for your time.
Try cloning the tables:
Private Function CopyTable(ByVal sourceTable As DataTable) As DataTable
Dim newTable As DataTable = sourceTable.Clone
For Each row As DataRow In sourceTable.Rows
newTable.ImportRow(row)
Next
Return newTable
End Function
Then your data sources would be referencing different sources:
Me.r_cbo_type.DataSource = CopyTable(ds.Tables(0))
Me.m_cbo_type.DataSource = CopyTable(ds.Tables(0))
do like this
Private Sub btn_update1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_update1.Click
If MsgBox("Are you sure to update?" & "", MsgBoxStyle.YesNo, "Confirmation") = MsgBoxResult.Yes = True Then
Dim transmode As String = vbNullString
Dim byair As String = vbNullString
Dim bysea As String = vbNullString
If rb_air.Checked = True Then
transmode = "A"
byair = txt_mserial.Text '.Substring(txt_mserial.TextLength - 4, 4)
bysea = vbNullString
ElseIf rb_sea.Checked = True Then
transmode = "B"
byair = vbNullString
bysea = txt_mserial.Text '.Substring(txt_mserial.TextLength - 4, 4)
End If
Try
If con.State = ConnectionState.Closed Then con.Open()
global_command = New SqlCommand("update ytmi_finished_products set rev_ctrl_no = '" & txt_mrev.Text & "', by_air = '" & byair & "', by_sea = '" & bysea & "', transport_mode = '" & transmode & "' where REPLACE(prod_no, '-', '') +'-'+ ISNULL(CONVERT(varchar(50), prod_sx), '') + prod_lvl = '" & txt_mpart.Text & "' and cast(serial_no as numeric) = '" & txt_mserial.Text & "' and req_box_qty = '" & txt_mqty.Text & "' and remarks is null", con)
global_command.ExecuteNonQuery()
global_command.Dispose()
MsgBox("Successfully Updated!", MsgBoxStyle.Information, "Message")
mclear()
Catch ex As Exception
MsgBox("Trace No 20: System Error or Data Error!" + Chr(13) + ex.Message + Chr(13) + "Please Contact Your System Administrator!", vbInformation, "Message")
End Try
End If
End Sub