如何从所有行的借方别名中减去贷方别名?

问题描述 投票:0回答:1

我正在开发一个分类帐管理系统,我有两种类型的报告,一种是分类帐报告,另一种是帐户报告。在帐户报告中,我从借方和贷方表中获取数据并显示在 dataGridView 中。

在 dataGridView 中,我有包含贷方 - 借方结果值的剩余别名,我还为第二行借方列分配此值,因为我希望下一个贷方金额应减去剩余金额。

此问题的原因是查询在每一行中显示相同的借方金额,导致下一个贷方金额再次减去实际借方金额,并且剩余余额不正确。

所以我想要第二行的贷方金额应从第二行中填充值的借方金额中减去,依此类推。

private void PopulateAccountReport()
        {
            string selectedName = comboBox2.SelectedItem.ToString();
            OleDbConnection connection = new OleDbConnection(connectionString);

            string query = "SELECT c.r_name AS 'Name', c.r_date AS 'Credit Date', c.r_amount AS 'Credit', d.d_date AS 'Debit Date', d.d_amount AS 'Debit', (d.d_amount - c.r_amount) AS 'Remaining', c.r_detail AS 'Credit Detail', d.d_detail AS 'Debit Detail' FROM credit c INNER JOIN debit d ON c.r_name = d.d_name WHERE c.r_name = @SelectedName ORDER BY c.r_sr ASC";

            using (OleDbCommand cmd = new OleDbCommand(query, connection))
            {
                cmd.Parameters.AddWithValue("@SelectedName", selectedName);
                connection.Open();
                DataTable dt = new DataTable();
                dt.Load(cmd.ExecuteReader());
                connection.Close();
                dataGridView1.DataSource = dt;
                decimal totalDebit = 0;
                decimal totalCredit = 0;

                foreach (DataRow row in dt.Rows)
                {
                    totalDebit += Convert.ToDecimal(row["'Debit'"]);
                    totalCredit += Convert.ToDecimal(row["'Credit'"]);

                    
                    int rowIndex = dt.Rows.IndexOf(row);
                    if (rowIndex < dt.Rows.Count - 1)
                    {
                        dt.Rows[rowIndex + 1]["'Debit'"] = row["'Remaining'"];
                    }
                }
                txt_tdebit.Text = totalDebit.ToString();
                txt_tcredit.Text = totalCredit.ToString();
            }
        }

`

查看图片了解预期结果

enter image description here

c# ms-access-2010
1个回答
0
投票
var runningBalance = 0;
var totalDebit = 0;
var totalCredit = 0;

for (int i = 0; i < dt.Rows.Count; i++)
{
    decimal credit = Convert.ToDecimal(dt.Rows[i]["'Credit'"]);
    decimal debit = Convert.ToDecimal(dt.Rows[i]["'Debit'"]);
    totalDebit += debit;
    totalCredit += credit;

    //Calculate remaining balance
    runningBalance += credit - debit;

    // Update the 'Remaining' value in the current row
    dt.Rows[i]["'Remaining'"] = runningBalance;

    // If not the last row, update the 'Debit' value in the next row
    if (i < dt.Rows.Count - 1)
    {
         dt.Rows[i + 1]["'Debit'"] = runningBalance;
    }
 }

txt_tdebit.Text = totalDebit.ToString();
txt_tcredit.Text = totalCredit.ToString();

您的代码在计算剩余金额时不会保持运行余额它需要累积每行的贷方和借方才能正确计算每行的剩余余额

© www.soinside.com 2019 - 2024. All rights reserved.