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.
If you want to achieve the distinct values for a specific field in the list, you can use the following two methods: 1. Using GroupBy and Select functions In this approach, you need to use two LINQ functions i.e., GroupBy and Select to get the list of unique field values. You can use the following code to have groupby and select in one query. 2.
LINQ sum is a method that comes under the aggregate functions; this method is used to calculate the sum or total numeric values present in the collections or lists. This query syntax supports VB.Net, and in C#, it is available in Queryable and Enumerable classes. The extension method Enumerable.Sum comes from the namespace System.Linq.
By using the LINQ query expression, we get the sum of numeric values in a collection. The sum () method is the extension of Enumerable.Sum which included in the namespace System.Linq. The sum () function calculates the sum of items which present in the list or collection, and it returns the sum of numeric values as a result.
To overcome this situation, you can use either of the following ways to have distinct values: In this method, GroupBy function is used to group the list which can either be a static list or a dynamic list. The Select operator is used to fetch the results from a list or a grouped list.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With