Reputation: 69
I had this problem setting a cell value based on the value of the next row.
For example;
Remarks Reference
A 50
A 25
B 5
-25
CASE 1:
If the value of the Next Cell.Row in column "Reference" is a POSITIVE number then the value of cell.row in column "Remarks" is "A".
CASE 2:
If the value of the Next Cell.Row in column "Reference" is a NEGATIVE number then the value of cell.row in column "Remarks" is "B".
I already tried this code but i cannot get the result i need.
Dim Bal As Decimal = 0
For Each r As DataGridViewRow In dgvSTSub.Rows
Bal = Bal + r.Cells(3).Value - r.Cells(1).Value
r.Cells(3).Value = Bal
If Bal > 0 Then
r.Cells(2).Value = Bal
ElseIf Bal < 0 Then
r.Cells(2).Value = r.Cells(3).Value
End If
Next
Please share me a code on how to do it.
Upvotes: 0
Views: 1035
Reputation: 3247
First of all I'd recommend using For
loop instead of ForEach
because iterating over rows becomes more convenient and easy.
Secondly, use ColumnNames
instead of Index
while accessing .Cells
, for eg: use .Cells("reference")
(reference is Column Name) instead of .Cells(1)
. I'm suggesting this because if in future you happen to re-order the columns your methods and functions won't get hindered, unless you change the name of your column.
Note: ColumnName here is not the the Header Text you see in the DataGridView UI. (hope you already know that)
As you haven't shown where you are setting remarks, this should get you some idea how to achieve it:
For index = 0 To DataGridView1.RowCount - 1
Dim nxt = 1
If (index + 1 < DataGridView1.RowCount) Then
nxt = DataGridView1.Rows(index + 1).Cells("reference").Value
End If
If (nxt) > 0 Then
DataGridView1.Rows(index).Cells("remark").Value = "A"
Else
DataGridView1.Rows(index).Cells("remark").Value = "B"
End If
Next
Dummy Output:
Remark Reference
A 13
B 21
A -33
B 41
A -54
Upvotes: 1