Get the sum of a datagridview column using Linq for a single id

I have two forms Form1(DGV1 & DGV2)and Form2(DGV3 & DGV4)with controls Datagridviewon both forms.

There Form1is a link to a button Form2where the user can add lines to Form1 datagridview(DGV1). In Form2 → (DGV3 and DGV4)the first column there is checkbox, and the user can select only one row at a time.

There Form2are two buttons in: DoneandAdd Items

When the user clicks the “Add Items” button, selecting rows one by one, the rows should be added Datagridviewto Form1, and when the “Finish” button is clicked, it is displayed Form1with all the rows that are added.

I have achieved this.

Columns in DGV1and DGV2are

DGV1 Columns

Sno Desciption SellQty ItemID
----------------------------
 1    ABC       0         1 
 2    XYZ       0         2

DGV2 Columns

Sno BatchNo SellQty ItemID
----------------------------
1    123       10         1
2    528       20         2
1    568       30         1
2    522       40         2

At boot time Form1, how can I get the amount SellQtydepending on ItemIDfor Form → DGv2and update the value SellQtyin DGV1.

Example: For ItemID=1 sum(SellQty)=40

therefore I need to assign this value DGV1 SellQty Column=40.

Please advice.

+5
source share
3 answers

Below is the total for ItemID == 1- (make sure you use the correct column names for your datagrid)

int total = DGV1.Rows.Cast<DataGridViewRow>()
                    .Where(r=> Convert.ToInt32(r.Cells["ItemID"].Value) == 1)
                    .Sum(t=> Convert.ToInt32(t.Cells["SellQty"].Value));

EDIT:

For your gridview update you can do:

for (int i = 0; i < DGV1.Rows.Count; i++)
{
    if (Convert.ToInt32(DGV1.Rows[i].Cells["ItemID"].Value) == 1)
        DGV1.Rows[i].Cells["SellQty"] = total;
}
+6
source

I think this code could be usfull

Textbox.Text = (from dr in MyDataSet.MyTable.AsEnumerable()
              where !dr.IsCR_TRANSFER_AMTNull()
              select dr.CR_TRANSFER_AMTNull).Sum().ToString();
+1
source

Another linq version of Mr. Habib's idea

var total = DGV1.Rows.Cast<DataGridViewRow>()
             .Where(c => int.Parse(c.Cells[IndeOfItemId].EditedFormattedValue.ToString()) == 1)
             .Sum(x => int.Parse(x.Cells[IndexOfSellQty].EditedFormattedValue.ToString()));
0
source

All Articles