I have a DataGrid that is populated from data of a simple, 1 row datatable. However, the datatable is not populating each of the columns as expected. Some cells are correct, while others are not. I am using a button click event to populate the datatable row.
Here is the XML code that defines the DataGrid:
<DataGrid x:Name="DG_TimedTest" HorizontalAlignment="Left" Height="86" Margin="0,118,0,0" VerticalAlignment="Top" Width="1296" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" ColumnHeaderHeight="60" Background="#FF232E3C" CanUserReorderColumns="False" CanUserResizeColumns="False" CanUserSortColumns="False" SelectionMode="Single" SelectionUnit="Cell" CanUserResizeRows="False" HorizontalGridLinesBrush="#FF688CAF" VerticalGridLinesBrush="#FF688CAF" HeadersVisibility="Column" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Disabled" Foreground="#FFC8E5FF" Grid.ColumnSpan="2" RowStyle="{DynamicResource RowStyle1}" ColumnHeaderStyle="{DynamicResource DGCHeaderStyle}" CanUserAddRows="False" EnableRowVirtualization="False">
<DataGrid.BindingGroup>
<BindingGroup/>
</DataGrid.BindingGroup>
</DataGrid>
Here is the XML code that defines the Header style:
<Style x:Key="DGCHeaderStyle" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Height" Value="48"/>
<Setter Property="Background" Value="#FF232E3C" />
<Setter Property="Foreground" Value="#FFC8E5FF"/>
<Setter Property="FontSize" Value="18" />
<Setter Property="FontFamily" Value="Calibri" />
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="BorderBrush" Value="#FF688CAF"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
Here is the XML code defining the Row style:
<Style x:Key="RowStyle1" TargetType= "{x:Type DataGridRow}">
<Setter Property="Background" Value="#FF232E3C"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Bottom"/>
Here is the code behind that defines the DataTable:
Public TestTimedTable As DataTable = New DataTable()
'Define the columns for the datatable
Dim MotorCCW3 As New DataColumn("Rotation" & vbCrLf & " (CCW)", GetType(Boolean))
Dim MotorCW3 As New DataColumn("Rotation" & vbCrLf & " (CW)", GetType(Boolean))
Dim AccelRate3 As New DataColumn("Accel Rate" & vbCrLf & " (RPM/S)", GetType(Integer))
Dim DecelRate3 As New DataColumn("Decel Rate" & vbCrLf & " (RPM/S)", GetType(Integer))
Dim Speed3 As New DataColumn("Speed" & vbCrLf & "(RPM)", GetType(Integer))
Dim LowFlowPump3 As New DataColumn(" Pump" & vbCrLf & "(Lo-Flo)", GetType(Boolean))
Dim HiFlowPump3 As New DataColumn(" Pump" & vbCrLf & "(Hi-Flo)", GetType(Boolean))
Dim Flow3 As New DataColumn("Flow" & vbCrLf & "(CCM)", GetType(Integer))
Dim FlowDev3 As New DataColumn("Flow Deviation" & vbCrLf & " (%)", GetType(Integer))
Dim TankTemp3 As New DataColumn("Tank Fluid" & vbCrLf & " (°F)", GetType(Integer))
Dim ExitFluidLowLim3 As New DataColumn("Exit Fluid LO-LIM" & vbCrLf & " (°F)", GetType(Integer))
Dim PartTempLim3 As New DataColumn("Part HI-LIM" & vbCrLf & " (°F)", GetType(Integer))
Dim TorqueLim3 As New DataColumn("Torque HI-LIM" & vbCrLf & " (Nm)", GetType(Single))
Dim Divert3 As New DataColumn("Divert Oil", GetType(Boolean))
Dim DivertTimeOn3 As New DataColumn(" Diverter On" & vbCrLf & " (S)", GetType(Integer))
Dim DivertTimeOff3 As New DataColumn(" Diverter Off" & vbCrLf & " (S)", GetType(Integer))
'Add the columns to the datatable
TestTimedTable.Columns.Add(MotorCCW3)
TestTimedTable.Columns.Add(MotorCW3)
TestTimedTable.Columns.Add(AccelRate3)
TestTimedTable.Columns.Add(DecelRate3)
TestTimedTable.Columns.Add(Speed3)
TestTimedTable.Columns.Add(LowFlowPump3)
TestTimedTable.Columns.Add(HiFlowPump3)
TestTimedTable.Columns.Add(Flow3)
TestTimedTable.Columns.Add(FlowDev3)
TestTimedTable.Columns.Add(TankTemp3)
TestTimedTable.Columns.Add(ExitFluidLowLim3)
TestTimedTable.Columns.Add(PartTempLim3)
TestTimedTable.Columns.Add(TorqueLim3)
TestTimedTable.Columns.Add(Divert3)
TestTimedTable.Columns.Add(DivertTimeOn3)
TestTimedTable.Columns.Add(DivertTimeOff3)
'Set the ItemsSource for the DataGrid as the DataTable
DG_TimedTest.ItemsSource = TestTimedTable.DefaultView
Via a button click event, populate a row with some data and add the row to the DataTable:
'Button click event, populate the datatable
Private Sub MyButton2_Click(sender As Object, e As RoutedEventArgs) Handles MyButton2.Click
Dim i As Integer = 35
Dim ii As Integer = 45
Dim s As Single = 3.14
Dim b As Boolean = True
Dim bb As Boolean = False
TestTimedTable.TableName = "Test_Timed_Table"
TestTimedTable.Rows.Add(b, b, i, ii, i, b, b, i, ii, i, ii, i, s, b, i, ii)
End Sub
Here is what the DataTable visualizer looks like, appears fine.
Here is the front end DataGrid (First 12 cells)
Here is an image of the remaining cells of the DataGrid:
The Datagrid is not being populated with the DataTable data all the way through. Some cells are not populating correctly, starting at the "Pump (Lo-Flo)" column. Any ideas what I require to do to fix the anomalies?
Thank you
Removing the space before the header column names has fixed the problem. Apparently putting a space before the start of the column name will cause an anomaly.
Here is the updated code defining the columns. Spaces removed before the start of the column names:
Dim MotorCCW3 As New DataColumn("Rotation" & vbCrLf & " (CCW)", GetType(Boolean))
Dim MotorCW3 As New DataColumn("Rotation" & vbCrLf & " (CW)", GetType(Boolean))
Dim AccelRate3 As New DataColumn("Accel Rate" & vbCrLf & " (RPM/S)", GetType(Integer))
Dim DecelRate3 As New DataColumn("Decel Rate" & vbCrLf & " (RPM/S)", GetType(Integer))
Dim Speed3 As New DataColumn("Speed" & vbCrLf & "(RPM)", GetType(Integer))
Dim LowFlowPump3 As New DataColumn("Pump" & vbCrLf & "(Lo-Flo)", GetType(Boolean))
Dim HiFlowPump3 As New DataColumn("Pump" & vbCrLf & "(Hi-Flo)", GetType(Boolean))
Dim Flow3 As New DataColumn("Flow" & vbCrLf & "(CCM)", GetType(Integer))
Dim FlowDev3 As New DataColumn("Flow Deviation" & vbCrLf & " (%)", GetType(Integer))
Dim TankTemp3 As New DataColumn("Tank Fluid" & vbCrLf & " (°F)", GetType(Integer))
Dim ExitFluidLowLim3 As New DataColumn("Exit Fluid LO-LIM" & vbCrLf & " (°F)", GetType(Integer))
Dim PartTempLim3 As New DataColumn("Part HI-LIM" & vbCrLf & " (°F)", GetType(Integer))
Dim TorqueLim3 As New DataColumn("Torque HI-LIM" & vbCrLf & " (Nm)", GetType(Single))
Dim Divert3 As New DataColumn("Divert Oil", GetType(Boolean))
Dim DivertTimeOn3 As New DataColumn("Diverter On" & vbCrLf & " (S)", GetType(Integer))
Dim DivertTimeOff3 As New DataColumn("Diverter Off" & vbCrLf & " (S)", GetType(Integer))
Related
What my program supposed to do : My goal is to create a windows service which acts as a mediator between multiple SQL databases. In total there are 3 different tables in 3 different servers In detail, when this service runs it should oversee the data in the "Table1" and copy it to the "Table2" in periodical time(every 1 minute). But tricky part is it cannot paste duplicate records, has to check for "Table2" 's ID field and validate for not pasting the same record with the same ID.I've added a diagram for understanding purposes of what my goal is
What I've done : So far I've developed the code completely but the issue is it only copies data from one table(specifically "NOR_LABOR" according to the diagram I've attached) to "DEV_Test_Nor_Data" in the "MES_DEV" Database(con1 to con2). According to the diagram con1, con3, con4 are tables "NOR_LABOR", "SETTER_LABOR" and "wrap_labor" respectively. con2 is the destination which is "MES_DEV" DB.
Can anybody figure out why does other table's data(con3 to con2 & con4 to con2) won't copy?
My code - Data Collector
Imports System.Configuration
Imports System.Data.SqlClient
Public Class DataCollector
Dim con1, con2, con3, con4 As New SqlConnection
Dim timer1 As Timers.Timer
Dim p_oConn As New Wisys.AllSystem.ConnectionInfo
Protected Overrides Sub OnStart(ByVal args() As String)
con1 = New SqlConnection("Data Source=NORMAC-CTMS\SQLEXPRESS;Database=Normac Data;Integrated Security=true")
con1.Open()
con2 = New SqlConnection("Data Source=STLEDGSQL01;Database=MES_DEV;Integrated Security=true")
con2.Open()
con3 = New SqlConnection("Data Source=201706-SETTER1\SQLEXPRESS;Database=Edge;Integrated Security=true")
con3.Open()
con4 = New SqlConnection("Data Source=PRINTER\SQLEXPRESS;Database=Wrapper Data;Integrated Security=true")
con4.Open()
timer1 = New Timers.Timer()
timer1.Interval = 5000
AddHandler timer1.Elapsed, AddressOf OnTimedEvent
timer1.Enabled = True
FileIO.WriteLog("Service has started")
End Sub
Protected Overrides Sub OnStop()
timer1.Enabled = False
FileIO.WriteLog("Service has stopped")
con1.Close()
con2.Close()
con3.Close()
con4.Close()
End Sub
Private Sub OnTimedEvent(obj As Object, e As EventArgs)
Dim cmd1, cmd2, cmd3 As SqlCommand
'Connecting the Normac Data table
Dim da1 As SqlDataAdapter = New SqlDataAdapter("select ID, trx_date, work_order, department, work_center, operation_no, operator, total_labor_hours, feet_produced, item_no, posted, labor_feet_produced from NOR_LABOR", con1)
Dim cb1 As SqlCommandBuilder = New SqlCommandBuilder(da1)
Dim dt1 As DataTable = New DataTable()
da1.Fill(dt1)
'Connecting the Setter_Labor table
Dim da2 As SqlDataAdapter = New SqlDataAdapter("select ID, trx_date, work_order, department, work_center, operation_no, operator, total_labor_hours, labor_feet_produced, item_no, posted from Setter_Labor", con3)
Dim cb2 As SqlCommandBuilder = New SqlCommandBuilder(da2)
Dim dt2 As DataTable = New DataTable()
da2.Fill(dt2)
'Connecting the Wrap_Labor table
Dim da3 As SqlDataAdapter = New SqlDataAdapter("select ID, trx_date, work_order, Department, work_center, operation_no, operator, total_labor_hrs, job_start, job_end, qty_ordered, qty_produced, item_no, lot_no, default_bin, posted, wrapped, total_shift_hrs, check_emp, machine, operation_complete from wrap_labor", con4)
Dim cb3 As SqlCommandBuilder = New SqlCommandBuilder(da3)
Dim dt3 As DataTable = New DataTable()
da3.Fill(dt3)
Dim i, j, k As Integer
'Inserting into DEV_Test_Nor_Data table
For Each dr As DataRow In dt1.Rows
cmd1 = New SqlCommand("Insert into DEV_Test_Nor_Data values('" & dr(0) & "','" & dr(1) & "','" & dr(2) & "','" & dr(3) & "','" & dr(4) & "','" & dr(5) & "','" & dr(6) & "','" & dr(7) & "','" & dr(8) & "','" & dr(9) & "','" & dr(10) & "','" & dr(11) & "')", con2)
i = cmd1.ExecuteNonQuery()
Next
'Inserting into DEV_Test_Set_Lbr table
For Each dr As DataRow In dt2.Rows
cmd2 = New SqlCommand("Insert into DEV_Test_Set_Lbr values('" & dr(0) & "','" & dr(1) & "','" & dr(2) & "','" & dr(3) & "','" & dr(4) & "','" & dr(5) & "','" & dr(6) & "','" & dr(7) & "','" & dr(8) & "','" & dr(9) & "','" & dr(10) & "')", con2)
j = cmd2.ExecuteNonQuery()
Next
'Inserting into DEV_Test_Wrp_Lbr table
For Each dr As DataRow In dt3.Rows
cmd3 = New SqlCommand("Insert into DEV_Test_Wrp_Lbr values('" & dr(0) & "','" & dr(1) & "','" & dr(2) & "','" & dr(3) & "','" & dr(4) & "','" & dr(5) & "','" & dr(6) & "','" & dr(7) & "','" & dr(8) & "','" & dr(9) & "','" & dr(10) & "','" & dr(11) & "','" & dr(12) & "','" & dr(13) & "','" & dr(14) & "','" & dr(15) & "','" & dr(16) & "','" & dr(17) & "','" & dr(18) & "','" & dr(19) & "','" & dr(20) & "')", con2)
k = cmd3.ExecuteNonQuery()
Next
da1.Update(dt1)
cmd1.Dispose()
dt1.Dispose()
da1.Dispose()
da2.Update(dt2)
cmd2.Dispose()
dt2.Dispose()
da2.Dispose()
da3.Update(dt3)
cmd3.Dispose()
dt3.Dispose()
da3.Dispose()
End Sub
End Class
Reference2
Reference3
Reference4
See if this helps. It may be the parameterized queries are your entire problem.
Public Class DataCollector
'Question text said one minute
Private timer1 As New Timers.Timer(60000)
Protected Overrides Sub OnStart(ByVal args() As String)
AddHandler timer1.Elapsed, AddressOf OnTimedEvent
timer1.Enabled = True
FileIO.WriteLog("Service has started")
End Sub
Protected Overrides Sub OnStop()
timer1.Enabled = False
FileIO.WriteLog("Service has stopped")
End Sub
Private Sub OnTimedEvent(obj As Object, e As EventArgs)
' DEV_Test_Nor_Data Table
ProcessOneTable("DEV_Test_Nor_Data", 12,
"Data Source=NORMAC-CTMS\SQLEXPRESS;Database=Normac Data;Integrated Security=true",
"SELECT ID, trx_date, work_order, department, work_center, operation_no, operator, total_labor_hours, feet_produced, item_no, posted, labor_feet_produced FROM NOR_LABOR"
)
' DEV_Test_Set_Lbr Table
ProcessOneTable("DEV_Test_Set_Lbr", 11,
"Data Source=201706-SETTER1\SQLEXPRESS;Database=Edge;Integrated Security=true",
"SELECT ID, trx_date, work_order, department, work_center, operation_no, operator, total_labor_hours, labor_feet_produced, item_no, posted from Setter_Labor"
)
' DEV_Test_Wrp_Lbr Table
ProcessOneTable("DEV_Test_Wrp_Lbr", 21,
"Data Source=PRINTER\SQLEXPRESS;Database=Wrapper Data;Integrated Security=true",
"SELECT ID, trx_date, work_order, Department, work_center, operation_no, operator, total_labor_hrs, job_start, job_end, qty_ordered, qty_produced, item_no, lot_no, default_bin, posted, wrapped, total_shift_hrs, check_emp, machine, operation_complete from wrap_labor"
)
End Sub
Private EdgeConnStr As String = "Data Source=STLEDGSQL01;Database=MES_DEV;Integrated Security=true"
Private Sub ProcessOneTable(destTableName As String, ParameterCount As Integer, sourceConnectionString AS String, sourceSql As String)
Dim data As New DataTable()
Using sourceConn As New SqlConnection(sourceConnectionString), _
da As New SqlDataAdapter(sourceSql, sourceConn)
da.Fill(data)
End Using
Dim paramList As String = String.Join(",", Enumerable.Range(0, ParameterCount).Select(Function(p) $"#p{p}"))
' Assumes first parateter (#p0) is always the ID.
Dim sql As String = $"INSERT INTO {destTableName} SELECT {paramList} WHERE NOT EXISTS(SELECT ID FROM {destTableName} WHERE ID = #p0)"
Using cn As New SqlConnection(EdgeConnStr), _
cmd As New SqlCommand(sql, cn)
For i As Integer = 0 To ParameterCount - 1
cmd.Parameters.Add($"#p{i}", SqlDbType.VarChar)
Next i
cn.Open()
For Each dr As DataRow In data.Rows
For i As Integer = 0 to ParameterCount - 1
cmd.Parameters(i).Value = dr(i)
Next i
cmd.ExecuteNonQuery()
Next dr
End Using
End Sub
End Class
It sounds like you also need to worry about merging the data, but start with this anyway; it fixes the HUGE GAPING SECURITY ISSUE in the original code, as well as isolating the important part of the code down to the minimum possible method size. This will make it easier to refactor just that part to also worry about what IDs may already exist... but I'll let you make an attempt at that yourself first (hint: INSERT + SELECT + WHERE NOT EXISTS() all in the same query)
I have create a library management system. here if I want to update a book's particular record its updating all the records in the SQL-server database. how can I write code for update a particular record only. here is my code,
Private Sub btnedit_Click(sender As Object, e As EventArgs) Handles btnedit.Click
con.ConnectionString = "data source=hp-pc\sqlexpress; initial catalog=Library_DB;integrated security= true"
con.Open()
Dim comd As New SqlCommand("update Book set Book_Id='" & TextBox1.Text & "',Bk_Name='" & TextBox2.Text & "',Author_Name='" & TextBox3.Text & "', Year_of_release='" & TextBox4.Text & "',Availability_of_bks='" & TextBox5.Text & "'", con)
comd.ExecuteNonQuery()
MessageBox.Show("Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Add a WHERE clause in your SQL command to specify which book will be updated..
use the ID number of the book you want to update.
and avoid concatenating in your sql command, use parameter #
Dim comd As New SqlCommand("update Book set Book_Id=#bookID, Bk_Name=#bkName, Author_Name=#author, Year_of_release=#release, Availability_of_bks=#avail WHERE Book_Id=#whereID", con)
comd.Parameters.Add("#bookID", SqlDbType.String).Value = TextBox1.Text
comd.Parameters.Add("#bkName", SqlDbType.String).Value = TextBox2.Text
comd.Parameters.Add("#author", SqlDbType.String).Value = TextBox3.Text
comd.Parameters.Add("#release", SqlDbType.String).Value = TextBox4.Text
comd.Parameters.Add("#avail", SqlDbType.String).Value = TextBox5.Text
comd.Parameters.Add("#whereID", SqlDbType.String).Value = "Book ID HERE"
comd.ExecuteNonQuery()
MessageBox.Show("Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
You need to add a WHERE clause to your SqlCommand so that SQL Server knows what record to update. Without a WHERE clause, it will update the entire table. See below:
con.ConnectionString = "data source=hp-pc\sqlexpress; initial catalog=Library_DB;integrated security= true"
con.Open()
Dim comd As New SqlCommand("update Book set Book_Id='" & TextBox1.Text & "',Bk_Name='" & TextBox2.Text & "',Author_Name='" & TextBox3.Text & "', Year_of_release='" & TextBox4.Text & "',Availability_of_bks='" & TextBox5.Text & "' WHERE Book_Id='{**Put your book id here**}'", con)
comd.ExecuteNonQuery()
MessageBox.Show("Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Can someone please let me know what is wrong with this code? I have checked all lines for misspellings - this isnt the issue. All tables and queries are written as they exist in the db. Any help is appreciated.
Private Sub LoadArray()
'---------------------------
'---------------------------
'This procedure loads text into the 3rd column of the array
'---------------------------
'---------------------------
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim rsFiltered As DAO.Recordset
Dim strSQL As String
Dim i As Integer
strSQL = "SELECT tblProperties.Name, tbl1OpportuniyType.Type, qryPropertiesALLTypesALLTbls.TotalUnits, " _
& "qryPropertiesALLTypesALLTbls.EventStartTimeEachDay, qryPropertiesALLTypesALLTbls.EventEndTimeEachDay, " _
& "qryPropertiesALLTypesALLTbls.EventStartDate, qryPropertiesALLTypesALLTbls.EventStopDate, " _
& "qryPropertiesALLTypesALLTbls.TechOpsGroup, qryPropertiesALLTypesALLTbls.TechOpsResource " _
& "FROM tbl1OpportuniyType RIGHT JOIN (qryPropertiesALLTypesALLTbls INNER JOIN tblProperties ON qryPropertiesALLTypesALLTbls.[PropertyComplex_ID] = tblProperties.[PropertyComplex_ID]) ON tbl1OpportuniyType.[OpportunityType_ID] = tblProperties.OpportunityType " _
& "WHERE (((qryPropertiesALLTypesALLTbls.EventStartDate) Is Not Null));"
'Debug.Print strSQL
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)
'This line ensures that the recordset is populated
If Not rs.BOF And Not rs.EOF Then
'Loops through the Array using dates for the filter
For i = LBound(myArray) To UBound(myArray)
If myArray(i, 1) Then
'Filters recordset with array dates
rs.Filter = "[EventStartDate]= " & myArray(i, 0)
'Open up new recordset based on filter
Set rsFiltered = rs.OpenRecordset
'Loop through new recordset
Do While (Not rsFiltered.EOF)
'Adds text to the 3rd column of the array
myArray(i, 2) = myArray(i, 2) & vbNewLine _
& rsFiltered!Type & " - " & vbNewLine _
& rsFiltered!Name & " " _
& rsFiltered!EventStartDate & " - " _
& rsFiltered!EventStopDate & " " _
& rsFiltered!EventStartTimeEachDay & " - " _
& rsFiltered!TechOpsGroup & " " _
& rsFiltered!TechOpsResource & " " _
& vbNewLine
rsFiltered.MoveNext
Loop
End If
Next i
End If
rsFiltered.Close
rs.Close
'Sets objects to nothing
Set rsFiltered = Nothing
Set rs = Nothing
Set db = Nothing
End Sub
It isn't clear where myArray comes from, but the filter needs an adjustment to convert the date value to a string expression:
rs.Filter = "[EventStartDate] = #" & Format(myArray(i, 0), "yyyy\/mm\/dd") & "#"
I'm trying to copy a datatable from a vb.net form I've set up into an access database. I'm using a snippet of code (with some alterations) posted by another user (Casbar27, Records added to ms access database with vb 2010 not saving).
Back_EndDataSet.tblTest.Clear()
Dim adapter As New Back_EndDataSetTableAdapters.tblTestTableAdapter
Dim rowCode As DataRow = Back_EndDataSet.tblTest.NewtblTestRefreshxinRow
For Each row As DataRow In source.Rows
adapter.Fill(Back_EndDataSet.tblTest)
rowCode.Item(0) = row.Item(0)
rowCode.Item(1) = row.Item(1)
rowCode.Item(2) = row.Item(2)
rowCode.Item(3) = row.Item(3)
rowCode.Item(4) = row.Item(4)
rowCode.Item(5) = row.Item(5)
rowCode.Item(6) = row.Item(6)
rowCode.Item(7) = row.Item(7)
rowCode.Item(8) = row.Item(8)
rowCode.Item(9) = row.Item(9)
Back_EndDataSet.tblTest.AddtblTestRow(rowCode)
adapter.Update(Back_EndDataSet.tblTest)
Next
While this is working, it's slow and is producing multiples of the same record if it's run several times. I want this to wipe the access table on start and rewrite it, and preferably in under a minute. Any suggestions?
Following #Gord Thompson's suggestion I wrote an OleDbCommand to delete the table, and decided to keep going an rewrote my filling method using an OleDbCommand. It work's great, the completion speed is up and I no longer have duplicate records. Thanks Gord!
Private Sub UpdateDataBase(ByVal source As DataTable)
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= H:\AppDev\Visual Studio 2010\Projects\RawFixerTest1\Raw Fixer Back End.accdb")
Dim cmdClr As New OleDbCommand
Dim cmdFill As New OleDbCommand
Dim i = 0
con.Open()
cmdClr.CommandText = "DELETE * FROM tblTestRefreshxin"
cmdClr.Connection = con
cmdClr.ExecuteNonQuery()
cmdFill.Connection = con
For Each row As DataRow In source.Rows
cmdFill.CommandText = "INSERT INTO tblTestRefreshxin (numCode, featDesc, alphaCode, clientCode, DTMexclude, attrCode1, attrCode2, attrCode3, attrCode4, lineToPrev) VALUES(" & "'" & row.Item(0) & "','" & row.Item(1) & "','" & row.Item(2) & "','" & row.Item(3) & "','" & row.Item(4) & "','" & row.Item(5) & "','" & row.Item(6) & "','" & row.Item(7) & "','" & row.Item(8) & "','" & row.Item(9) & "')"
cmdFill.ExecuteNonQuery()
Next
con.Close()
End Sub
I just wanted to ask why my data duplicates and how can I prevent it?
NOTE: my SQL query are working properly, the only problem is that every data it saves are duplicated based on the last value of ctr
Here is my code:
For Each lvi As ListViewItem In lvReportFormat2.Items
Dim count = lvReportFormat2.Items.Count
Dim ctr = 0
Dim orderby = 0
label.Text = lvReportFormat2.Items(ctr).SubItems(4).Text
Do While ctr < count
Label1.Text = lvReportFormat2.Items(ctr).SubItems(4).Text
Execute("INSERT INTO tblrptChad (accountcode,accountdesc,Type,class,Orderby,ReportType,Formula,Show)VALUES ('" & IIf(lvReportFormat2.Items(ctr).SubItems(0).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(0).Text, "NULL") & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(1).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(1).Text, "NULL") & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(2).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(2).Text, "NULL") & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(3).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(3).Text, "NULL") & "','" & orderby & "','" & Val(IIf(lvReportFormat2.Items(ctr).SubItems(5).Text IsNot DBNull.Value, Val(lvReportFormat2.Items(ctr).SubItems(5).Text), 0)) & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(6).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(6).Text, "NULL") & "','" & Val(IIf(lvReportFormat2.Items(ctr).SubItems(7).Text IsNot DBNull.Value, Val(lvReportFormat2.Items(ctr).SubItems(7).Text), 0)) & "')")
ctr = ctr + 1
orderby = orderby + 1
Loop
Next
You are inserting duplicates of your records because you loop two times on the Items collection of your ListView. A first time with the foreach lvi ... Next statement and a second time with the Do While loop
A full answer to your question would require to introduce you to parameterized queries, but this involves to change radically your Execute method.
So for the immediate answer
Dim orderby = 0
For Each lvi As ListViewItem In lvReportFormat2.Items
Label1.Text = lvi.SubItems(4).Text
Execute("INSERT INTO tblrptChad "& _
"(accountcode,accountdesc,Type,class,Orderby," & _
"ReportType,Formula,Show) VALUES " & _
"('" & _
If(lvi.SubItems(0).Text IsNot DBNull.Value, _
lvi.SubItems(0).Text, "NULL") & "','" & _
If(lvi.SubItems(1).Text IsNot DBNull.Value, _
lvi.SubItems(1).Text, "NULL") & "','" & _
If(lvi.SubItems(2).Text IsNot DBNull.Value, _
lvi.SubItems(2).Text, "NULL") & "','" & _
If(lvi.SubItems(3).Text IsNot DBNull.Value, _
lvi.SubItems(3).Text, "NULL") & "','" & _
orderby & "','" & _
Val(If(lvi.SubItems(5).Text IsNot DBNull.Value, _
Val(lvi.SubItems(5).Text), 0)) & "','" & _
If(lvi.SubItems(6).Text IsNot DBNull.Value, _
lvi.SubItems(6).Text, "NULL") & "','" & _
Val(If(lvi.SubItems(7).Text IsNot DBNull.Value, _
Val(lvi.SubItems(7).Text), 0)) & "')")
orderby = orderby + 1
Next
lvi in the for each is the ListViewItem currently indexed.
This means that lvi is lvReportFormat2.Items(ctr)
As a side note, I am pretty sure that a string property like SubItems(x).Text cannot be a DBNull value, so all these IIF are pretty useless and can be removed. I let you try it.
Said that, you really should look at parameterized queries to simplify your command text removing all those string concatenations that are error prone to get it right (for example, did yuo check what happens if one of your subitems contains a text with an apostrophe?) and are the main vector for Sql Injection attacks.
TO SOLVE THE PROBLE YOU JUST NEED TO ADD "EXIT SUB" OUTSIDE THE LOOP
For Each lvi As ListViewItem In lvReportFormat2.Items
Dim count = lvReportFormat2.Items.Count
Dim ctr = 0
Dim orderby = 0
label.Text = lvReportFormat2.Items(ctr).SubItems(4).Text
Do While ctr < count
Label1.Text = lvReportFormat2.Items(ctr).SubItems(4).Text
Execute("INSERT INTO tblrptChad (accountcode,accountdesc,Type,class,Orderby,ReportType,Formula,Show)VALUES ('" & IIf(lvReportFormat2.Items(ctr).SubItems(0).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(0).Text, "NULL") & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(1).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(1).Text, "NULL") & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(2).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(2).Text, "NULL") & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(3).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(3).Text, "NULL") & "','" & orderby & "','" & Val(IIf(lvReportFormat2.Items(ctr).SubItems(5).Text IsNot DBNull.Value, Val(lvReportFormat2.Items(ctr).SubItems(5).Text), 0)) & "','" & IIf(lvReportFormat2.Items(ctr).SubItems(6).Text IsNot DBNull.Value, lvReportFormat2.Items(ctr).SubItems(6).Text, "NULL") & "','" & Val(IIf(lvReportFormat2.Items(ctr).SubItems(7).Text IsNot DBNull.Value, Val(lvReportFormat2.Items(ctr).SubItems(7).Text), 0)) & "')")
ctr = ctr + 1
orderby = orderby + 1
Loop
EXIT SUB
Next