Click here to Skip to main content
15,357,358 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this `datagridviewcartlist`  in vb.net

|Item          | Price  |   Qty     |  Total       | category|
|--------------|--------|-----------|--------------|---------|
|Chicken Pizza  | 10.99  |      1    |    10.99     | P       |
|Cheese Pizza  | 7.99   |      1    |    7.99      | P       |
|Pepsi         | 5.99   |      1    |    5.99      | D       |

I want to create a button where  it `combine selected row` with `other datagridviewcart rows` that have the same `category` to become like this

|Item                          | Price  |   Qty     |  Total       | category|
|------------------------------|--------|-----------|--------------|---------|
(Chicken Pizza * Cheese Pizza ) | 9.49   |     1     |    9.49      | P       |
|Pepsi                         | 5.99   |     1     |    5.99      | D       |


What I have tried:

my datagridview columns are (id,item,price,qty,total,p)
my database tablecart columns are (citem transno pid price qty total tdate tableno user status prefix cuisin)
Posted
Updated 19-Dec-21 3:25am

1 solution

There are several ways you could achieve this but without more details of how you populate the DataGridView in the first place, I am going to present a "brute force" method assuming the DataGridView is unbound.

Step 1: Sort the DataGridView on the category column e.g.
VB
datagridviewcartlist.Sort(datagridviewcartlist.Columns(4)
          ,System.ComponentModel.ListSortDirection.Ascending)
Step 2: Step through each row in the DGV calculating rolling total on price - you may have to have other totals - it is not clear why you have averaged prices of pizzas and are not totalling the quantity

Things to note:
- keep a variable that indicates the "current" category - start with a value that is not a valid category to get things rolling.
- start with a price total of 0 at the start and each time the category changes re-zero it.
- you will also need a variable to store the growing description - I suggest a String Builder How to: create strings using a StringBuilder - Visual Basic | Microsoft Docs[^]

E.g. (not tested)
VB
Dim TotPrice as Decimal = 0.0
Dim CountRows as Integer = 0
Dim PrevCategory as String = "XX"
Dim ExtendedDesc as StringBuilder = New StringBuilder("(")
For Each row As DataGridViewRow in datagridviewcartlist.Rows
     If row.Cells(4).Value <> PrevCategory and PrevCategory <> "XX" Then
          'Capture the average price 
          'Finalise the text description by removing the last * and adding a )
     Else
          ExtendedDesc.Append(row.Cells(4).Value & " * ")
          CountRows += 1
          TotPrice += row.Cells(2)
          ' etc ...
     End If
Next
Other things to note: How are you going to identify which rows to remove (and what problems do you think you might hit if you try to do this as your going through them in a loop?)

It might be easier to have a second DataGridView into which you just insert the calculated/merged rows.

Other options you might want to try
- Manipulate the DataSource of the DGV - e.g. Group the Datatable
- Do the grouping on the actual source of the DGV if it is bound data coming from a database
   
Comments
Member 15205573 31-Dec-21 17:05pm
   
hey CHILL60
Thank you for your effort
i will try to learn more about this string builder and see if your solution will work or not


however i managed to get this code from the software i wanted to copy this fusion feature from it's a php desktop application

what do you think about this code
//var fusionMode = 1;


function fusion(){
var fusionner = [];
var selectedTr = document.querySelectorAll('tr.current');

if (selectedTr.length > 1) {
var printServer = document.querySelector('tr.current').getAttribute('ds');
var fPrice = 0;
var fName = [];
var fId = [];
var biggestPrice = 0;

for (var i = 0; i < selectedTr.length; i++) {

var tid = selectedTr[i].getAttribute('rel');
var idInFood = findID(foodList , tid);
if (parseFloat(foodList[idInFood][3]) > biggestPrice ) biggestPrice = parseFloat(foodList[idInFood][3]);
fPrice += parseFloat(foodList[idInFood][3]);
fName.push( foodList[idInFood][2] ) ;
fId.push(tid);
document.querySelector('input[name="p_'+tid+'"]').remove();
}
fId = fId.join();
//fId = fName.join('/');
fName = fName.mergenames();
var MiddlePrice = Math.round (fPrice / selectedTr.length );
var MiddlePrice =(fusionMode == 1 ?MiddlePrice : biggestPrice );
var tableCont = "1"+fName+""+ MiddlePrice +"";
var inputContent = "";
$('#salesTable').append(tableCont);
//document.getElementById('salesTable').innerHTML = tableCont + document.getElementById('salesTable').innerHTML;
$('#salesForm').append(inputContent);


for (var i = 0; i < selectedTr.length; i++) {
selectedTr[i].remove();
}
} else {
document.getElementsByClassName('fusionBtn')[0].classList.add('blinkerror');
window.setTimeout(function(){document.getElementsByClassName('fusionBtn')[0].classList.remove('blinkerror');},500);
// alert('erreur !');
}
countAmount();
selectingTr();
}


Array.prototype.mergenames = function(){
var ar = this;
var m = this[0].split(' ')[0];
//console.log(m);
for (var i = 0; i < ar.length; i++) {
if (ar[i].split(' ').length > 1 && ar[i].indexOf(m)) ar[i] = ar[i].trim().replace(m, "");
}
return m+'('+ar.join(' - ')+')';
}






function findID(fl , x) {
var ret ='';
for (var i = 0; i < fl.length; i++) {
if (fl[i][0] == x) {ret =i; break;}
}
return ret
}
CHill60 4-Jan-22 2:54am
   
What do I think about that code? I think it is not VB and does not use a DataGridView.
Why do you think I would know anything about PHP when I tried to help you with a VB question?
What makes you think it is in any way relevant to your post?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900