HOW to merge and get the difference between 2 datatable - datatable

we've created a function that merge 2 datatable.
here's the code
Public Shared Function CompareTwoDataTable(ByVal dt1 As DataTable, ByVal dt2 As DataTable) As DataTable
dt1.Merge(dt2)
Dim d3 As DataTable = dt2.GetChanges()
Return d3
End Function
i was wondering if the code was incorrect or what, my point is i want to determine the difference between those 2 table and get their difference.
Thanks in advance

for those who view this, this is the code i've come up to
i've created a function that compares the 2 datatable using their ids
Public Shared Function CompareTwoDataTable(ByVal dt1 As DataTable, ByVal dt2 As DataTable) As DataTable
Dim rows_to_remove As New List(Of DataRow)()
For Each row1 As DataRow In dt1.Rows
For Each row2 As DataRow In dt2.Rows
If row1("ID").ToString() = row2("ID").ToString() Then
rows_to_remove.Add(row1)
End If
Next
Next
For Each row As DataRow In rows_to_remove
dt1.Rows.Remove(row)
dt1.AcceptChanges()
Next
Dim d3 As DataTable = dt1
Return d3
End Function
Hope it helps

Related

How do you add your queried datatable results into a new datatable

Can someone please help me fill my queried results into the existing datatable or a new datatable
''dt is filled with data from a csv file.
Dim dataRows As DataRow() = dt.Select("[Calendar year TEXT] = '2020'")
dt.Clear() 'Clear the datatable
dt.Rows.Add(dataRows) 'Add the result to the existing datatable or a new databletable if possible ?
So I've figured it out.
The reason I need a new DataTable is that I need to use it again in its original form later.
I could not attach the DataRow collection to my display control which is why I needed a new DataTable with the filtered results.
Private Function FilterDataTable(ByVal strQuery As String, ByVal dtRaw As DataTable)
Dim dataRows As DataRow() = dtRaw.Select(strQuery)
Dim dtFiltered As DataTable
dtFiltered = dtRaw.Clone() 'This is very important.
For Each drow As DataRow In dataRows
dtFiltered.ImportRow(drow) 'Add each filtered row to new DataTable.
Next
Return dtFiltered
End Function
Your dt.select will return an array of Datarow pointing to the rows in the datatable dt. Your dt.clear then clears the datatable and so will empty the dataRows array leaving you nothing left.
I'm not clear exactly what you are trying to do. I'm guessing you have a table that you want to filter and then discard all rows that don't match, leaving you a datatable to work with.
If so, here's a few options:
Work with the datarow array directly rather than the datatable. Is there really any need to convert the rows back to a datatable?
Create a new datatable to add the rows to, but don't clear the original table:
Dim dt As New DataTable ' Assume this is your populated table
Dim dataRows As DataRow() = dt.Select("[Calendar year TEXT] = '2020'")
Dim dtResults As DataTable = dt.Clone()
For Each row As DataRow In dr
dtResults.ImportRow(row)
Next
bare in mind any changes you make to the rows in dtResults will also affect the rows in dt as they both contain the same data
Depending on the size of your table and whether or not you really want to discard non matching rows, you could just remove all rows that don't match then work with the result:
Dim i As Integer = dt.Rows.Count - 1
While i >= 0
If dt(i).Item("Calendar") <> "Your test here" Then dt.Rows.Remove(dt(i))
i -= 1
End While

How do i set the celltype for a datagrid column?

I am adding a new column to a datagrid to store a row total of qty*Cost
When I try to add the column I get an exception saying
System.InvalidOperationException: 'Column cannot be added because its CellType property is null.'
I've tried to set the cell type but I can't get the type right
Dim dt As DataTable = Me.DsOppQuoteDetail.tblOppQuoteDetail
Dim dr As DataRow
Dim dc As New DataGridViewColumn
With dc
.HeaderText = "Item Total"
.Name = "UnitTotal"
.CellType = DataGridTextBox
End With
DGV_OppQuoteDetail.Columns.Insert(6, dc)
Setting the CellType to DataGridTextBox produces an error
If I change the the column to:
Dim dc As New DataGridTextBoxColumn
With dc
.HeaderText = "Item Total"
End With
DGV_OppQuoteDetail.Columns.Insert(6, dc)
then I can't insert it because it's the wrong type for the DataGrid.Insert command
Dim dc As New DataGridViewTextBoxColumn
dc.HeaderText = "SomeText"
dc.Name = "colWhateverName"
DGV_OppQuoteDetail.Columns.Add(dc)
Try this and let me know. Only slightly different in terms of wording. Also from your code snippet it seems fine but make sure you don't add any rows before adding a column.

DataTable: create rows dynamically according to the number of checkboxes selected in the checkbox List

I am trying to create a DataTable the number of rows of which needs to be created automatically according to the number of checkboxes checked in my checkbox list:
Private Function GetRoomTypeIds() As DataTable
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn(1) {New DataColumn("Id", GetType(Integer)), New DataColumn("RoomTypeId", GetType(Integer))})
dt.Rows.Add(txtId1.Text, chkRoomTypes.SelectedValue)
Return dt
End Function
I would need to add something like:
"For Each Checkbox checked in my checkbox list generate the corresponding number of rows."
Thanks
I solved as per below code:
Private Function GetRoomTypeIds() As DataTable
Dim selectedItems = From s In chkRoomTypes.Items.Cast(Of ListItem)
Where s.Selected
Select s
Dim itemTable As DataTable
itemTable = New DataTable("SelectedItems")
Dim column1 As DataColumn = New DataColumn("RateTypeId")
column1.DataType = System.Type.GetType("System.Int32")
Dim column2 As DataColumn = New DataColumn("RoomTypeId")
column2.DataType = System.Type.GetType("System.Int32")
itemTable.Columns.Add(column1)
itemTable.Columns.Add(column2)
Dim Row As DataRow
For Each item In selectedItems
Row = itemTable.NewRow()
Row("RateTypeId") = Convert.ToInt32(txtId1.Text)
Row("RoomTypeId") = item.Value
itemTable.Rows.Add(Row)
Next
Return itemTable
End Function
Thanks

Converting VBA code to google sheets script for auto sort

I am looking for assistance on a script for google sheets for an auto sort function that runs when I update the sheet with new information. The sheet name is "Summary All Events". I have data starting in Row 4, Columns A:J. I would like to auto sort any data from A4:J1000 by column 1 (A) in ascending order. Can anyone help me?
Here is the script I am running in VBA for Excel. But now I need to convert it into a script for Google Sheets.
Public Sub Worksheet_Change(ByVal Target As Excel.Range)
If Target.Column = 1 Then
Dim lastRow As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
Range("A4:J" & lastRow).Sort Key1:=Range("A4:A" & lastRow), Order1:=xlAscending, Header:=xlNo
End If
End Sub
Try the following code:
function onEdit(e) {
var sheet = e.source.getActiveSheet();
if (sheet.getName() == 'Sheet1') {
var r = e.range;
if (r.columnStart == 1 && r.rowStart >= 4)
sheet.getRange('A4:J').sort({column:1,ascending:true});
}
};
Now, whenever any user will edit any cell in range "A4:A", the above code will auto sort the range A4:J by column A in ascending order.

FILTER OLAP CUBE WITH VBA

I am trying to update an OLAP pivotfilter with the value of another cell (not in a pivot table).
The code I have is as follows:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'This line stops the worksheet updating on every change, it only updates when
'cell C1 or C2 is touched
If Intersect(Target, Range("C1:C2")) Is Nothing Then Exit Sub
'Set the Variables to be used
Dim pt As PivotTable
Dim Field As PivotField
Dim NewStock As String
'Here you amend to suit your data
Set pt = ActiveSheet.PivotTables("PivotFilter")
'The activesheet is named "Top1_Value"
Set Field = pt.PivotFields("[StockCode].[Stock Code_SKU].[Stock Code_SKU]")
NewStock = ActiveSheet.Range("C1").Value
'This updates and refreshes the PIVOT table
With pt
Field.ClearAllFilters
Field.VisibleItemsList = NewStock
pt.RefreshTable
End With
End Sub
Any assistance to resolve would be appreciated.

Resources