且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取datagrid中列的所有值并添加它们

更新时间:2023-02-23 13:17:26

循环遍历所有Datagrid的行。



在循环中,找到行的列值并使用变量求和。
Loop through all the rows of Datagrid.

Inside the loop, find the column value for the row and sum that using a variable.


您可以在用于绑定数据网格的数据源中执行此操作,而不是在datagridview中执行求和。



例如,如果您使用数据表作为绑定datagrid的源,然后你可以找到像这样的总和 -

Instead of doing the sum in the datagridview, you can do that in the datasource you are using to bind the datagrid.

For example, if you are using datatable as the source for binding datagrid then you can find the sum doing something like-
double total = 0;
foreach (var myRow in myTable)
{
    total += double.Parse(myRow["MyValue"].ToString());
}





要在绑定数据网格之外的其他地方取回数据表,你可以写一些像 -



To get back the datatable at some other place than the binding datagrid, you write something like-

Datatable dt = (Datatable) myDatagrid.ItemsSource;





希望,它有助于:)



Hope, it helps :)