Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将一列中的数字之和与另一列中的数字之和相乘?访问C#_C#_Database_Ms Access - Fatal编程技术网

将一列中的数字之和与另一列中的数字之和相乘?访问C#

将一列中的数字之和与另一列中的数字之和相乘?访问C#,c#,database,ms-access,C#,Database,Ms Access,此程序在数据网格视图中显示数据库信息。我需要将第1列中的所有数字相加,将第3列中的所有数字相加,然后将两个总和相乘 此代码仅与最后一行的第1列和第3列相乘。有什么建议吗 这是我第一次连接到数据库,所以如果这是一个愚蠢的问题,我很抱歉 foreach (DataRow currentRow in itemDS.Tables[0].Rows) { // add to data grid view

此程序在数据网格视图中显示数据库信息。我需要将第1列中的所有数字相加,将第3列中的所有数字相加,然后将两个总和相乘

此代码仅与最后一行的第1列和第3列相乘。有什么建议吗

这是我第一次连接到数据库,所以如果这是一个愚蠢的问题,我很抱歉

                foreach (DataRow currentRow in itemDS.Tables[0].Rows)
                {
                    // add to data grid view
                    invoiceDataGridView.Rows.Add(currentRow[1].ToString(),   currentRow[2].ToString(), currentRow[3].ToString());

                    var itemQuant = Convert.ToDecimal(currentRow[1]);
                    var priceEach = Convert.ToDecimal(currentRow[3]);

                    decimal subTotal = itemQuant * priceEach;

                    subTotalOutput.Text = subTotal.ToString();
                }

你的意思是你不确定如何在循环结构中保持一个连续的总数?如果是:

decimal total = 0; //declare outside the foreach

foreach (DataRow currentRow in itemDS.Tables[0].Rows)
                {
                    // add to data grid view
                    invoiceDataGridView.Rows.Add(currentRow[1].ToString(),   currentRow[2].ToString(), currentRow[3].ToString());

                    var itemQuant = Convert.ToDecimal(currentRow[1]);
                    var priceEach = Convert.ToDecimal(currentRow[3]);

                    decimal subTotal = itemQuant * priceEach;

                    total += subTotal;
                }

//do something with total here, after for each finishes

可以使用linq获取列的和

var sum = itemDS.Tables[0].AsEnumerable().Sum(dr => dr.Field<int>("value"));
var sum=itemDS.Tables[0].AsEnumerable().sum(dr=>dr.Field(“value”);
“value”
将是itemDS中数据表的列名。您必须在此处指定列名

取下一列的和,就像上面的语句一样。把它加起来


希望这有帮助:)

啊,是的!非常感谢你。Thant完全按照我的需要工作:)