I have two DataGridView
the following columns:
- CODE
- NAME
- AMOUNT.
Through TextBox
and% botón
, I'm passing values from DataGridView
to another, adding new rows.
Is it possible to achieve that when finding identical values in CODIGO
and NOMBRE
, increase the CANTIDAD
, updating that row, without creating a new one?
This is my code:
Dim newRow As DataRowView = DirectCast(Pedidos_GeneralBindingSource.AddNew(), DataRowView)
newRow("CODIGO") = CODIGOTextBox.Text
newRow("NOMBRE") = NOMBRETextBox.Text
newRow("CANTIDAD") = CANTIDADTextBox.Text
EDITED
This is the code I have so far:
Dim DT_Segundo As New DataTable
DT_Segundo.Columns.Add("CODIGO", Type.[GetType]("System.String"))
DT_Segundo.Columns.Add("NOMBRE", Type.[GetType]("System.String"))
DT_Segundo.Columns.Add("CANTIDAD", Type.[GetType]("System.String"))
Dim primarykey(1) As DataColumn
primarykey(0) = DT_Segundo.Columns("CODIGO")
DT_Segundo.PrimaryKey = primarykey
DataGridView2.DataSource = DT_Segundo
Dim CODIGOi As String
Dim NOMBREi As String
Dim CANTIDADi As String
CODIGOi = CODIGOTextBox.Text
NOMBREi = NOMBRETextBox.Text
CANTIDADi = CANTIDADTextBox.Text
If Not DT_Segundo.Rows.Find(CODIGOi) Is Nothing Then
DT_Segundo.Rows.Find(CODIGOi).Item("CANTIDAD") = DT_Segundo.Rows.Find(CODIGOi).Item("CANTIDAD") + CANTIDADi
Else
DT_Segundo.Rows.Add(CODIGOi, NOMBREi, CANTIDADi)
End If
My problem now is that when I run it, I replace the existing values of my DataGridView2 with a row created from the values stored in the TextBox. Do not add new rows or add the amount for those that have the same value in the "CODE" column.
EDITED 2
Add the COST column to calculate value and finally I could achieve it with another code, I leave it for the one that can serve:
Dim Found As Boolean = False
Dim total As Double = Convert.ToDouble(COSTOTextBox.Text) * 1
If Pedidos_GeneralDataGridView.Rows.Count > 0 Then
For Each row As DataGridViewRow In Pedidos_GeneralDataGridView.Rows
If Convert.ToString(row.Cells(0).Value) = CODIGOTextBox.Text Then
row.Cells(2).Value = Convert.ToString(1 + Convert.ToInt16(row.Cells(2).Value))
row.Cells(3).Value = Convert.ToDouble(row.Cells(3).Value) + Convert.ToDouble(COSTOTextBox.Text)
Found = True
End If
Next
If Not Found Then
Dim newRow As DataRowView = DirectCast(Pedidos_GeneralBindingSource.AddNew(), DataRowView)
newRow("CODIGO") = CODIGOTextBox.Text
newRow("NOMBRE") = NOMBRETextBox.Text
newRow("CANTIDAD") = CANTIDADTextBox.Text
newRow("COSTO") = COSTOTextBox.Text
End If
End If