5
votes

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

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

There are two buttons on Form2: Done and Add Items

When user clicks on Add Items by selecting the rows one after another,the rows must be added to the datagridview on Form1 and when Done button is clicked, Form1 should be displayed with all the rows that are added.

I have achieved this.

The columns in DGV1 and DGV2 are

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

During the loading of Form1, how can I get the sum of SellQty depending on ItemID for Form → DGv2 and update the value of SellQty in DGV1.

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

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

Please advice.

3

3 Answers

8
votes

Following will give you total quantity 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 updating gridview 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;
}
1
votes

I think this code maybe usfull

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

Another version of linq from idea of Mr. Habib

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()));