WPF ListBox - moving items up and down - wpf

In an older WinForms app this worked, but in WPF it will move the item only once, the only current workaround is the save it to the back end DB, open again and move one more space. The list items are supplied by a DataTable
Private Sub Reports_BalanceSheet_ListBoxMoveUp(LB As ListBox, DT As DataTable, DisplayName As String, Optional MasterListBox As ListBox = Nothing)
Try
Dim StartIndex As Integer = LB.SelectedIndex
Dim CatID As Integer = 0
'Update the datasource
Dim SR() As DataRow
If DisplayName = "Name" Then
SR = DT.Select("ID > 0 AND FormID = " & Form_ID, Nothing)
Else
CatID = MasterListBox.SelectedValue
'Check that the positions are correct
If DataChanged = False Then
Dim vRowID As Integer = 0
For Each Row As DataRow In DT.Rows
If Row("FormID") = Form_ID And Row("CatID") = CatID Then
Row("Position") = vRowID
vRowID += 1
End If
Next
End If
SR = DT.Select("ID > 0 AND FormID = " & Form_ID & " AND CatID = " & CatID, "Position")
End If
Dim vString As String = ""
Dim vUpperID As Integer = 0
Dim vCurrentID As Integer = 0
For Each Row As DataRow In SR
Dim vPos As Integer = Row("Position")
If vPos = StartIndex - 1 Then
vUpperID = Row("ID")
End If
If vPos = StartIndex Then
vCurrentID = Row("ID")
End If
Next
If Not vUpperID = 0 And Not vCurrentID = 0 Then
DT.Select("ID = " & vUpperID)(0)("Position") = StartIndex
DT.Select("ID = " & vCurrentID)(0)("Position") = StartIndex - 1
If DisplayName = "Name" Then
DT.DefaultView.RowFilter = "FormID = " & Form_ID
Else
DT.DefaultView.RowFilter = "FormID = " & Form_ID & " AND CatID = " & CatID
End If
DT.DefaultView.Sort = "Position"
DT = DT.DefaultView.ToTable
DT.AcceptChanges()
With LB
.SelectedValuePath = "ID"
.DisplayMemberPath = DisplayName
.ItemsSource = DT.DefaultView
.SelectedValue = vCurrentID
.UpdateLayout()
End With
End If
Catch ex As Exception
EmailError(ex)
End Try
End Sub

Got it working this way (and with less code) :-)
Dim StartIndex As Integer = LB.SelectedIndex
Dim vTotalRows As Integer = DT.Rows.Count - 1
If Not StartIndex = vTotalRows Then
Dim vSelected As DataRow = DT.Rows(StartIndex)
Dim vNew As DataRow = DT.NewRow()
vNew.ItemArray = vSelected.ItemArray
DT.Rows.Remove(vSelected)
DT.Rows.InsertAt(vNew, StartIndex + 1)
LB.SelectedIndex = StartIndex + 1
Dim vPos As Integer = 0
For Each Row As DataRow In DT.Rows
Row("Position") = vPos
vPos += 1
Next
End If

Related

VB: How to Transfer Data from a DataGrid to Online SQL Table dynamically?

I'm very new to VB, I was able to get data from a proprietary database into a DataGrid view, however now, I need to export that data to an online SQL table, similar to what is happening with the DataGrid
This is the code that works for the Datagrid, I have tried a couple of options, but currently I have NO idea on how to generate the same data dynamically to an online SQl table (of which I now virtually nothing)
Private Sub Search(cabID As String, docTypeID() As String)
Dim lSearch As New Generic.List(Of SDKClientAccess.HitlistSearchItem)
For Each ctrl As Control In Me.panFields.Controls
If TypeOf ctrl Is TextBox AndAlso Not ctrl.Text Is Nothing AndAlso ctrl.Text.Length > 0 Then
Dim hsItem As New SDKClientAccess.HitlistSearchItem
hsItem.MetaField = SDKClientAccess.SearchMetaFields.State
hsItem.Mode = SDKClientAccess.SearchModes.AND
hsItem.FieldID = ctrl.Tag.ToString
hsItem.Operator = SDKClientAccess.SearchOperators.Equal
hsItem.StartValue = ctrl.Text
'hsItem.EndValue = "" use when Operator is set to FDClientAccess.SearchOperators.Between
lSearch.Add(hsItem)
End If
Next
Dim resHitlist As SDKClientAccess.HitlistResults = _cAccess.GetHitlist(cabID, docTypeID, lSearch.ToArray)
If resHitlist Is Nothing Then
MessageBox.Show("No matches found!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
dgHitlist.DataSource = Nothing
txtDocGUID.Text = Nothing
Else
Dim dt As New DataTable
dt.Columns.Add("ActRevision")
dt.Columns.Add("Deleted")
dt.Columns.Add("Guid")
dt.Columns.Add("Pages")
dt.Columns.Add("RefGuid")
dt.Columns.Add("Size")
dt.Columns.Add("State")
For Each Val As SDKClientAccess.HitlistCell In resHitlist.Tables(0).Rows(0).Values
dt.Columns.Add(Val.ID)
Next
For Each hRow As SDKClientAccess.HitlistRow In resHitlist.Tables(0).Rows
Dim dr As DataRow = dt.NewRow()
dr("ActRevision") = hRow.ActRevision
dr("Deleted") = hRow.Deleted
dr("Guid") = hRow.Guid
dr("Pages") = hRow.Pages
dr("RefGuid") = hRow.RefGuid
dr("Size") = hRow.Size
dr("State") = hRow.State
For Each Val As SDKClientAccess.HitlistCell In hRow.Values
dr(Val.ID) = Val.Value
Next
dt.Rows.Add(dr)
Next
dgHitlist.DataSource = dt
txtDocGUID.Text = DirectCast(dgHitlist.DataSource, DataTable).Rows(dgHitlist.CurrentRowIndex)("GUID").ToString
End If
End Sub
I'd really appreciate help in solving this!
Thanks to everyone!
Ok, I was able to solve my problem. However, if you know of a better or more efficient way, please let me know.
Private Sub Search(cabID As String, docTypeID() As String)
Dim conStr As String = "Server=xxxxxxx.database.windows.net;Database=ECM_Project;User Id=xxxxx;Password=xxxxxx"
Dim lSearch As New Generic.List(Of SDKClientAccess.HitlistSearchItem)
For Each ctrl As Control In Me.panFields.Controls
If TypeOf ctrl Is TextBox AndAlso Not ctrl.Text Is Nothing AndAlso ctrl.Text.Length > 0 Then
Dim hsItem As New SDKClientAccess.HitlistSearchItem
hsItem.MetaField = SDKClientAccess.SearchMetaFields.State
hsItem.Mode = SDKClientAccess.SearchModes.AND
hsItem.FieldID = ctrl.Tag.ToString
hsItem.Operator = SDKClientAccess.SearchOperators.Equal
hsItem.StartValue = ctrl.Text
lSearch.Add(hsItem)
End If
Next
Dim resHitlist As SDKClientAccess.HitlistResults = _cAccess.GetHitlist(cabID, docTypeID, lSearch.ToArray)
If resHitlist Is Nothing Then
MessageBox.Show("No matches found!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
dgHitlist.DataSource = Nothing
txtDocGUID.Text = Nothing
Else
Dim dt As New DataTable
dt.Columns.Add("ActRevision")
dt.Columns.Add("Deleted")
dt.Columns.Add("Guid")
dt.Columns.Add("Pages")
dt.Columns.Add("RefGuid")
dt.Columns.Add("Size")
dt.Columns.Add("State")
For Each Val As SDKClientAccess.HitlistCell In resHitlist.Tables(0).Rows(0).Values
dt.Columns.Add(Val.ID)
Next
For Each hRow As SDKClientAccess.HitlistRow In resHitlist.Tables(0).Rows
Dim dr As DataRow = dt.NewRow()
dr("ActRevision") = hRow.ActRevision
dr("Deleted") = hRow.Deleted
dr("Guid") = hRow.Guid
dr("Pages") = hRow.Pages
dr("RefGuid") = hRow.RefGuid
dr("Size") = hRow.Size
dr("State") = hRow.State
For Each Val As SDKClientAccess.HitlistCell In hRow.Values
dr(Val.ID) = Val.Value
Dim Filename As String = ""
Dim MainCategoryID As String = ""
Dim SubCategoryID As String = ""
Dim MainClassificationID As String = ""
Dim SubClassificatioID As String = ""
Dim PropertyCode As String = ""
Dim PropertyName As String = ""
Dim Region As String = ""
Dim Sector As String = ""
If (Val.ID = "3511DC38") Then
Filename = CStr(Val.Value)
End If
If (Val.ID = "935FDDCF") Then
MainCategoryID = CStr(Val.Value)
End If
If (Val.ID = "3A668646") Then
SubCategoryID = CStr(Val.Value)
End If
If (Val.ID = "824C0FD3") Then
MainClassificationID = CStr(Val.Value)
End If
If (Val.ID = "3A317B82") Then
SubClassificatioID = CStr(Val.Value)
End If
If (Val.ID = "C4078214") Then
PropertyCode = CStr(Val.Value)
End If
If (Val.ID = "36AC71D6") Then
PropertyName = CStr(Val.Value)
End If
If (Val.ID = "3A317B82") Then
Region = CStr(Val.Value)
End If
If (Val.ID = "3A317B82") Then
Sector = CStr(Val.Value)
End If
Dim LVRow As String = ""
Dim objCon As New SqlConnection(conStr)
Dim obj As SqlCommand
Dim strSQL As String = ""
If objCon.State = ConnectionState.Closed Then
Try
objCon.Open()
obj = objCon.CreateCommand()
strSQL = "INSERT INTO [dbo].[ECM_GridItems_v2]([ID],[FileName],[Length],[MainCategoryID],[SubCategoryID],[MainClassificationID],[SubClassificatioID],[PropertyCode],[PropertyName],[Region],[Sector]) VALUES('" + hRow.Guid + "','" + Filename + "','" + hRow.Size.ToString() + "','" + MainCategoryID + "','" + SubCategoryID + "','" + MainClassificationID + "','" + SubClassificatioID + "' ,'" + PropertyCode + "','" + PropertyName + "','" + Region + "' ,'" + Sector + "')"
obj.CommandText = strSQL
obj.ExecuteNonQuery()
objCon.Close()
objCon = Nothing
Catch ex As Exception
objCon.Close()
objCon = Nothing
MessageBox.Show(ex.Message)
End Try
End If
Next
dt.Rows.Add(dr)
Next
dgHitlist.DataSource = dt
txtDocGUID.Text = DirectCast(dgHitlist.DataSource, DataTable).Rows(dgHitlist.CurrentRowIndex)("GUID").ToString
End If
End Sub

how to populate array of controls (labels) using database vb.net

I am doing my homework but stuck on a part. Problem is, How can i populate seat number in array of controls(labels) using database. I already created labels and a class to retrieve all rows from database but how can i apply it in main form and populate labels.
--------------------------Class---------------------------------------
Public Shared Function getOneRow(PK As Integer) As datMovieTimes
Dim returnRow As New datMovieTimes(0)
Dim connDB As New SqlConnection
connDB.ConnectionString = Conn.getConnectionString
Dim command As New SqlCommand
command.Connection = connDB
command.CommandType = CommandType.Text
command.CommandText = SQLStatements.SELECT_1_BY_ID
command.Parameters.AddWithValue("#Key", PK)
Try
connDB.Open()
Dim dR As IDataReader = command.ExecuteReader
If dR.Read() Then
returnRow.showingID = PK
If Not IsDBNull(dR(Fields.movieID)) Then returnRow.movieID = dR(Fields.movieID)
If Not IsDBNull(dR(Fields.dateTime)) Then returnRow.dateTime = dR(Fields.dateTime)
If Not IsDBNull(dR(Fields.isActive)) Then returnRow.isActive = dR(Fields.isActive)
End If
Catch ex As Exception
Console.WriteLine(Err.Description)
End Try
Return returnRow
End Function
Public Shared Function getAllRows() As Generic.List(Of datMovieTimes)
Dim returnRows As New Generic.List(Of datMovieTimes)
Dim connDB As New SqlConnection
connDB.ConnectionString = Conn.getConnectionString
Dim command As New SqlCommand
command.Connection = connDB
command.CommandType = CommandType.Text
command.CommandText = SQLStatements.SELECT_ALL
Try
connDB.Open()
Dim dR As IDataReader = command.ExecuteReader
Do While dR.Read()
Dim Row As New datMovieTimes(0)
If Not IsDBNull(dR(Fields.showingID)) Then Row.showingID = dR(Fields.showingID)
If Not IsDBNull(dR(Fields.movieID)) Then Row.movieID = dR(Fields.movieID)
If Not IsDBNull(dR(Fields.dateTime)) Then Row.dateTime = dR(Fields.dateTime)
If Not IsDBNull(dR(Fields.isActive)) Then Row.isActive = dR(Fields.isActive)
returnRows.Add(Row)
Loop
Catch ex As Exception
Console.WriteLine(Err.Description)
End Try
Return returnRows
End Function
-----------------------------main form-----------------------------------------
Public Sub createSeat()
Dim S1 As Label
For X As Integer = 1 To _MAX_X
For Y As Integer = 1 To _MAX_Y
S1 = New Label
S1.Height = 25
S1.Width = 25
S1.BackColor = Color.LightGreen
S1.Top = 100 + (X - 1) * (S1.Height + 5)
S1.Left = 200 + (Y - 1) * (S1.Width + 5)
S1.TextAlign = ContentAlignment.MiddleCenter
S1.Text = Y.ToString
AddHandler S1.Click, AddressOf GenericLabel_Click
Me.Controls.Add(S1)
_SeatArray(X, Y) = S1
Next
Next
For X As Integer = 0 To 9
_AlphaLabel(X) = New Label
_AlphaLabel(X).Height = 25
_AlphaLabel(X).Width = 25
_AlphaLabel(X).BackColor = Color.Transparent
_AlphaLabel(X).Top = 130 + (X - 1) * (_AlphaLabel(X).Height + 6)
_AlphaLabel(X).Left = 170
_AlphaLabel(X).Text = _AlphaName(X)
Me.Controls.Add(_AlphaLabel(X))
Next
End Sub
Private Sub GenericLabel_Click(sender As Object, e As EventArgs)
Dim L As New Label
L = DirectCast(sender, Label)
If L.BackColor = Color.LightGreen Then
L.BackColor = Color.Orange
clickLess -= 1
ElseIf L.BackColor = Color.Orange Then
L.BackColor = Color.LightGreen
clickLess += 1
End If
clickCount += 1
Me.lblRemainingCount.Text = clickLess.ToString
Me.nudTicketsCount.Value = clickCount
If clickLess <= 0 Then
MsgBox("No more seats left.", MsgBoxStyle.OkOnly, "House Full")
End If
End Sub
Database pic
When creating labels, insert one more line:
S1.Name = "MyLabel" & X & Y
When accessing the label:
Dim MyCurrentLabel as Label
MyCurrentLabel = CType("MyLabel" & X & Y, Label)
Then you can do things with the current label:
MyCurrentLabel.Text = "Hello World"
current image
Now it is something like this, so it want to change the colour to red if it is paid according to database.
Thanks
I found the answer, sorry i forgot to mention it because i was busy in completing the project
----------------------Seat creation----------------------------------------
Public Sub createSeat()
Dim S1 As Label
Dim numValue As Integer = 1
For X As Integer = 1 To _MAX_X
For Y As Integer = 1 To _MAX_Y
S1 = New Label
S1.Height = 25
S1.Width = 25
S1.BackColor = Color.LightGreen
S1.Top = 180 + (X - 1) * (S1.Height + 5)
S1.Left = 200 + (Y - 1) * (S1.Width + 5)
S1.TextAlign = ContentAlignment.MiddleCenter
S1.Text = Y.ToString
' S1.Text = numValue
S1.Name = "Label" & numValue
AddHandler S1.Click, AddressOf GenericLabel_Click
Me.Controls.Add(S1)
_SeatArray(X, Y) = S1
numValue += 1
Next
Next
For X As Integer = 0 To 9
_AlphaLabel(X) = New Label
_AlphaLabel(X).Height = 25
_AlphaLabel(X).Width = 25
_AlphaLabel(X).BackColor = Color.Transparent
_AlphaLabel(X).Top = 210 + (X - 1) * (_AlphaLabel(X).Height + 6)
_AlphaLabel(X).Left = 170
_AlphaLabel(X).Text = _AlphaName(X)
Me.Controls.Add(_AlphaLabel(X))
Next
End Sub
-------------------------------populate seat number----------------------------------
Public Sub populateSeatNumber()
Dim connectionString As String = DBL.Conn.getConnectionString
Dim connection As New SqlConnection(connectionString)
connection.Open()
Dim selectStatement As String = "SELECT * FROM datTicketsSold"
Dim selectCommand As New SqlCommand(selectStatement, connection)
Dim daSoldTickets As New SqlDataAdapter(selectCommand)
Dim dsSoldTickets As DataSet = New DataSet
daSoldTickets.Fill(dsSoldTickets, "datTicketsSold")
connection.Close()
Dim dtTickets As DataTable = dsSoldTickets.Tables("datTicketsSold")
Dim row As DataRow
For Each row In dtTickets.Rows
If row(3) = True Then
CType(Controls("Label" & row(2)), Label).BackColor = Color.Red
redCounter += 1
Else
CType(Controls("Label" & row(2)), Label).BackColor = Color.Yellow
yellowCounter += 1
End If
Next
Me.lblReservedCount.Text = yellowCounter.ToString
Me.lblSoldCount.Text = redCounter.ToString
End Sub
Thanks everyone

WPF ListBox values from another selected ListBox item then move up and down

We have a series of ListBoxes - when an item in the main ListBox is selected the relevant values are displayed in the sub ListBox. This works as intended...
We also have the ability to move items up or down, and this works as intended...
When the main ListBox has the SelectionChanged event wired up the ability to move items up and down in the sub list box stops working. Comment that out and up/down works again in the sub ListBox... I must have overlooked something glaringly obvious but after numerous changes still can't get it to work
Main ListBox SelectionChanged
Private Sub Reports_CashFlow_ListBox_IndexChanged(ByVal MainLB As String, ByVal NominalLB As String, ByVal NomDT As DataTable)
Try
Dim LB As LBx = ReportCashFlow_Grid.FindName(MainLB)
If LB.SelectedIndex = -1 Then
Exit Sub
End If
Dim NomLB As LBx = ReportCashFlow_Grid.FindName(NominalLB)
If NomLB Is Nothing Then
Exit Sub
End If
If LB.SelectedValue Is Nothing Then
Exit Sub
End If
If LB.SelectedValue.GetType.Name Is Nothing Then
Exit Sub
End If
If LB.SelectedValue.GetType.Name <> "DataRowView" Then
Dim CatID As Integer = LB.SelectedValue
Dim DV As New DataView(NomDT)
DV.RowFilter = "CatID = " & CatID & " AND FormID = " & Form_ID
DV.Sort = "Position"
With NomLB
.ItemsSource = DV
.Items.Refresh()
End With
LB.ScrollIntoView(LB.SelectedItem)
End If
Catch ex As Exception
EmailError(ex)
End Try
End Sub
Move items up
Private Sub Reports_BalanceSheet_ListBoxMoveUp(LB As ListBox, DT As DataTable, DisplayName As String, Optional MasterListBox As ListBox = Nothing)
Try
Dim StartIndex As Integer = LB.SelectedIndex
If StartIndex = -1 Then
AppBoxValidation("You have not selected an item to move up!")
Exit Sub
End If
If Not StartIndex = 0 Then
Dim CatID As Integer = 0
If DisplayName = "NomName" Then
CatID = MasterListBox.SelectedValue
End If
Dim vSelected As DataRow = DT.Rows(StartIndex)
Dim vNew As DataRow = DT.NewRow()
vNew.ItemArray = vSelected.ItemArray
DT.Rows.Remove(vSelected)
DT.Rows.InsertAt(vNew, StartIndex - 1)
DT.AcceptChanges()
LB.SelectedIndex = StartIndex - 1
Dim vPos As Integer = 0
For Each Row As DataRow In DT.Rows
If Not CatID = 0 Then
If Row("CatID") = CatID Then
Row("Position") = vPos
vPos += 1
End If
Else
Row("Position") = vPos
vPos += 1
End If
Next
LB.Items.Refresh()
End If
Catch ex As Exception
EmailError(ex)
End Try
End Sub
Turns out the issue related to subsets of data in the DataView - so needed to find the correct index for the selected item and the replacement index in the entire back-end table
Private Sub Reports_BalanceSheet_ListBoxMoveUp(LB As ListBox, DT As DataTable, DisplayName As String, Optional MasterListBox As ListBox = Nothing)
Try
Dim StartIndex As Integer = LB.SelectedIndex
If StartIndex = -1 Then
AppBoxValidation("You have not selected an item to move up!")
Exit Sub
End If
If Not StartIndex = 0 Then
Dim CatID As Integer = 0
If DisplayName = "NomName" Then
CatID = MasterListBox.SelectedValue
'As the view could be a subset of data we need to find the actual back end DB index
Dim SelectedID As Integer = LB.SelectedValue
Dim DR() As DataRow = DT.Select("ID = " & SelectedID, Nothing)
Dim vIndex As Integer = DT.Rows.IndexOf(DR(0))
Dim vCurrentPos As Integer = DR(0)("Position")
'Find the index of the one above in the grid
Dim DR2() As DataRow = DT.Select("CatID = " & CatID & " AND Position = " & vCurrentPos - 1, Nothing)
Dim vIndex2 As Integer = DT.Rows.IndexOf(DR2(0))
Dim vSelected As DataRow = DT.Rows(vIndex)
Dim vNew As DataRow = DT.NewRow()
vNew.ItemArray = vSelected.ItemArray
DT.Rows.Remove(vSelected)
DT.Rows.InsertAt(vNew, vIndex2)
DT.AcceptChanges()
Else
Dim vSelected As DataRow = DT.Rows(StartIndex)
Dim vNew As DataRow = DT.NewRow()
vNew.ItemArray = vSelected.ItemArray
DT.Rows.Remove(vSelected)
DT.Rows.InsertAt(vNew, StartIndex - 1)
DT.AcceptChanges()
End If
Dim vPos As Integer = 0
For Each Row As DataRow In DT.Rows
If Not CatID = 0 Then
If Row("CatID") = CatID Then
Row("Position") = vPos
vPos += 1
End If
Else
Row("Position") = vPos
vPos += 1
End If
Next
LB.SelectedIndex = StartIndex - 1
End If
Catch ex As Exception
EmailError(ex)
End Try
End Sub

Background Worker and ODBC Query

I want to run the fetching of a Database into a background worker but it seems to be crashing without Visual Studio returning me an error in my code.
Here's the code in the DoWork:
Private Sub ITSM_Fetch_BW_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles ITSM_Fetch_BW.DoWork
Dim sql As String = "xxxx"
Dim ConnString As String = "DRIVER={AR System ODBC Driver};ARServer=xxxx;ARServerPort=xxxx;ARPrivateRpcSocket=xxxx;UID=xxxx;PWD=xxxx;ARAuthentication=;ARUseUnderscores=1;SERVER=NotTheServer"
Dim connection As New Odbc.OdbcConnection(ConnString)
connection.Open()
Dim ODBC_Command As New Odbc.OdbcCommand(sql, connection)
Dim ODBC_reader As Odbc.OdbcDataReader
'Load the Data into the local Memory
ODBC_reader = ODBC_Command.ExecuteReader
e.Result = ODBC_reader
ODBC_reader.Close()
End Sub
Private Sub ITSM_Fetch_BW_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles ITSM_Fetch_BW.RunWorkerCompleted
Data = New DataTable
Data.Load(e.Result)
Dim Count_ToDo(5) As String
Count_ToDo(0) = "Product_Name"
Count_ToDo(1) = "Status"
Count_ToDo(2) = "Language"
Count_ToDo(3) = "Assigned_Group"
Count_ToDo(4) = "Priority"
Count_ToDo(5) = "Company"
For Each Item As String In Count_ToDo
Dim i As Integer = 0
Dim ITEM_Count(0, 1) As String
For Each Ticket As DataRow In Data.Rows
'PART FOR THE CI
If IsDBNull(Ticket.Item(Item)) = False Then
Dim IsInIndex As Integer = -1
If i = 0 Then
ITEM_Count(0, 0) = Ticket.Item(Item)
ITEM_Count(0, 1) = 1
Else
For x As Integer = 0 To ITEM_Count.GetLength(0) - 1
If ITEM_Count(x, 0) = Ticket.Item(Item) Then
IsInIndex = x
End If
Next
If IsInIndex = -1 Then
Dim ITEM_Count_Temp(ITEM_Count.GetLength(0), ITEM_Count.GetLength(0)) As String
ITEM_Count_Temp = ITEM_Count
ReDim ITEM_Count(ITEM_Count.GetLength(0), 1)
For x As Integer = 0 To ITEM_Count_Temp.GetLength(0) - 1
For y As Integer = 0 To ITEM_Count_Temp.GetLength(1) - 1
ITEM_Count(x, y) = ITEM_Count_Temp(x, y)
Next
Next
ITEM_Count(ITEM_Count.GetLength(0) - 1, 0) = Ticket.Item(Item)
ITEM_Count(ITEM_Count.GetLength(0) - 1, 1) = 1
Else
ITEM_Count(IsInIndex, 1) = ITEM_Count(IsInIndex, 1) + 1
End If
End If
Else
'IF NULL
End If
i = i + 1
Next
'CI_COUNT FILLING
'ORDERING BY COUNT
Dim ITEM_obj = New List(Of obj)
Dim ITEM_ToObj As String = ""
Dim ITEMCount_ToObj As String = ""
For x As Integer = 0 To ITEM_Count.GetLength(0) - 1
ITEM_ToObj = ITEM_Count(x, 0)
ITEMCount_ToObj = ITEM_Count(x, 1)
ITEM_obj.Add(New obj(ITEM_ToObj, ITEMCount_ToObj))
Next
ITEM_obj = OrderItem(ITEM_obj)
Dim Item_Count_listview As ListViewItem
For Each Itemobj As obj In ITEM_obj
Dim Transfer_Array(2) As String
Transfer_Array(0) = Itemobj.Item
Transfer_Array(1) = Itemobj.Item_Count
Item_Count_listview = New ListViewItem(Transfer_Array)
Select Case Item
Case "Product_Name"
CI_Count_Table.Items.Add(Item_Count_listview)
Case "Status"
Status_Count_Table.Items.Add(Item_Count_listview)
Case "Language"
Language_Count_Table.Items.Add(Item_Count_listview)
Case "Assigned_Group"
AssignedGroup_Count_Table.Items.Add(Item_Count_listview)
Case "Priority"
Priority_Count_Table.Items.Add(Item_Count_listview)
Case "Company"
LOB_Count_Table.Items.Add(Item_Count_listview)
Case Else
MsgBox("No Category Of this type exist. Programming Issue. Item is: " & Item)
End Select
Next
Next
End Sub
What is not possible to run into a background worker like this?
regards,

vba loop through fields in recordset while another recordset is not EOF

I am writing some code for an access database (Access 2010) and need to extract non-empty fields from a table into another (tbl_TempProducts to tbl_BrandsStocked). Whilst doing this the row with the fields I want to 'copy and paste' from needs to be split into various rows of another table. The first value of the record in tbl_TempProducts should be used as the first value in every new record in tbl_BrandsStocked as long as the values being transferred are in the same record as the record we are transferring from. I want to create a new record in tbl_BrandsStocked for every 7th field in tbl_TempProducts.
Please see Diagram provided HERE
The code works but the order in which it 'pastes' the code into the destination table is incorrect.
Please forgive me if this is not clear enough as this is my first post!
I will post more information if needed.. :)
Please see code below:
Private Sub btnTransfer_Click()
Dim dbs As DAO.Database
Dim temp As DAO.Recordset
Dim bStocked As DAO.Recordset
Dim fld As DAO.Field
Dim AutoID As String
Dim Product As String
Dim varProd As String
Dim PackSize As String
Dim priceType As String
Dim casesSold As String
Dim accountNumber As Integer
Dim firstRun As Boolean
Dim counter As Integer
Set dbs = CurrentDb
Set temp = dbs.OpenRecordset("SELECT * FROM tbl_TempProducts WHERE id IS NOT NULL")
Set bStocked = dbs.OpenRecordset("SELECT * FROM tbl_BrandsStocked")
counter = 0
firstRun = True
temp.MoveFirst
Do While temp.EOF = False
For Each fld In temp.Fields
If fld.Name <> "" Then
If counter = 1 Then
AutoID = Nz(fld.value, "")
If AutoID <> "" Then
AutoID = Nz(fld.value, "")
bStocked.AddNew
bStocked!AccountNo = AutoID
bStocked.upDate
If accountNumber <> AutoID Then
On Error Resume Next
accountNumber = AutoID
End If
Else
counter = counter - 1
End If
ElseIf counter = 2 Then
Product = Nz(fld.value, "")
If Product <> "" Then
bStocked.MoveLast
bStocked.Edit
bStocked!Brand = Product
bStocked.upDate
Else
counter = counter - 1
End If
ElseIf counter = 3 Then
varProduct = Nz(fld.value, "")
If varProduct <> "" Then
bStocked.MoveLast
bStocked.Edit
bStocked!Variation = varProduct
bStocked.upDate
Else
counter = counter - 1
End If
ElseIf counter = 4 Then
PackSize = Nz(fld.value, "")
If PackSize <> "" Then
bStocked.MoveLast
bStocked.Edit
bStocked!PackSize = PackSize
bStocked.upDate
Else
counter = counter - 1
End If
ElseIf counter = 5 Then
priceType = Nz(fld.value, "")
If priceType <> "" Then
bStocked.MoveLast
bStocked.Edit
bStocked![RRP-PMP] = priceType
bStocked.upDate
Else
counter = counter - 1
End If
ElseIf counter = 6 Then
casesSold = Nz(fld.value, "")
If casesSold <> "" Then
bStocked.MoveLast
bStocked.Edit
bStocked!CPW = casesSold
bStocked.upDate
Else
counter = counter - 1
End If
End If
End If
counter = counter + 1
If counter >= 7 Then
counter = 2
bStocked.AddNew
bStocked!AccountNo = accountNumber
bStocked.upDate
End If
Next
temp.MoveNext
counter = 0
firstRun = True
Loop
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE * FROM [tbl_BrandsStocked] WHERE [Brand] Is null"
DoCmd.SetWarnings True
Set dbs = Nothing
Set temp = Nothing
Set bStocked = Nothing
Set fld = Nothing
End Sub
I have solved this problem now. The main reason I was getting incorrect values in the destination table was because using the "accountNumber" variable was not necessary. Instead I used the "AutoID" variable value as the first field on the destination table when looping through the code.
Very simple fix but it did take me a while unfortunately, hence the reason for posting as I needed an extra pair of eyes!
Working Code:
Private Sub btnTransfer_Click()
Dim dbs As DAO.Database
Dim temp As DAO.Recordset
Dim bStocked As DAO.Recordset
Dim fld As DAO.Field
Dim AutoID As String
Dim Product As String
Dim varProd As String
Dim PackSize As String
Dim priceType As String
Dim casesSold As String
Dim accountNumber As Integer
Dim counter As Integer
Set dbs = CurrentDb
Set temp = dbs.OpenRecordset("SELECT * FROM tbl_TempProducts WHERE id IS NOT NULL")
Set bStocked = dbs.OpenRecordset("SELECT * FROM tbl_BrandsStocked")
counter = 0
firstRun = True
accountNumber = 0
AutoID = 0
temp.MoveFirst
Do While temp.EOF = False
For Each fld In temp.Fields
If fld.Name <> "" Then
If counter = 1 Then
AutoID = Nz(fld.value, "")
If AutoID <> "" Then
AutoID = Nz(fld.value, "")
bStocked.AddNew
bStocked!AccountNo = AutoID
bStocked.upDate
Else
counter = counter - 1
End If
ElseIf counter = 2 Then
Product = Nz(fld.value, "")
If Product <> "" Then
bStocked.MoveLast
bStocked.Edit
bStocked!Brand = Product
bStocked.upDate
Else
counter = counter - 1
End If
ElseIf counter = 3 Then
varProduct = Nz(fld.value, "")
If varProduct <> "" Then
bStocked.MoveLast
bStocked.Edit
bStocked!Variation = varProduct
bStocked.upDate
Else
counter = counter - 1
End If
ElseIf counter = 4 Then
PackSize = Nz(fld.value, "")
If PackSize <> "" Then
bStocked.MoveLast
bStocked.Edit
bStocked!PackSize = PackSize
bStocked.upDate
Else
counter = counter - 1
End If
ElseIf counter = 5 Then
priceType = Nz(fld.value, "")
If priceType <> "" Then
bStocked.MoveLast
bStocked.Edit
bStocked![RRP-PMP] = priceType
bStocked.upDate
Else
counter = counter - 1
End If
ElseIf counter = 6 Then
casesSold = Nz(fld.value, "")
If casesSold <> "" Then
bStocked.MoveLast
bStocked.Edit
bStocked!CPW = casesSold
bStocked.upDate
Else
counter = counter - 1
End If
End If
End If
counter = counter + 1
If counter >= 7 Then
counter = 2
bStocked.AddNew
bStocked!AccountNo = AutoID
bStocked.upDate
End If
Next
temp.MoveNext
counter = 0
Loop
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE * FROM [tbl_BrandsStocked] WHERE [Brand] Is null"
DoCmd.SetWarnings True
Set dbs = Nothing
Set temp = Nothing
Set bStocked = Nothing
Set fld = Nothing
End Sub
In addition to posting sample data, you should review your code:
You start with counter = 0, but don't have a case for this, so the first field will always be ignored. Intentionally?
firstRun is set but never used
Instead of all the bStocked.MoveLast, .Edit, .Update you should have one current record in bStocked that you write to. This would make your code much better readable.
Edit
I suggest a structure like this:
strValue = Nz(fld.value, "")
If strValue <> "" Then
Select Case counter
Case 1: accountNumber = Val(strValue) ' add error handling!
bStocked.AddNew
bStocked!AccountNo = accountNumber
Case 2: bStocked!Brand = strValue ' Product
Case 3: bStocked!Variation = strValue ' varProduct
' etc 4..6
End Select
counter = counter + 1
If counter >= 7 Then
bStocked.upDate ' save new record
bStocked.AddNew
bStocked!AccountNo = accountNumber
counter = 2
End If
Else
' For an empty field you simply move to the next field
End If
Next fld
' save last record
bStocked.upDate

Resources