I want to sum a datagrid column with where condition which data is loaded from an excel file. I use the following code to sum but its not show result at a time. It shows again again up to finish. But i want to sum datagrid column at a time and i want to sum with multiple condition. How can i do it?
C#
decimal sum = 0;
for (int i = 0; i < DataGridImp.Rows.Count - 1; i++)
{
if (DataGridImp.Rows[i].Cells["L.AC_No"].Value.ToString() == "90100000010"
&& DataGridImp.Rows[i].Cells["L.AC_No"].Value != null)
{
sum += Convert.ToDecimal(DataGridImp.Rows[i].Cells["L.Balance"].Value) / 100000;
MessageBox.Show(Convert.ToString(sum.ToString("#.##")), "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Amit MohantyRank #112 · 20K reputationPosted Jun 28, 2023, 7:02 AM EDT
decimal sum = 0; for (int i = 0; i < DataGridImp.Rows.Count - 1; i++) { string acNo = DataGridImp.Rows[i].Cells["L.AC_No"].Value?.ToString(); if (acNo != null && (acNo == "90100000010" || acNo == "90100000012" || acNo == "90100000015" || acNo == "90100000009")) { sum += Convert.ToDecimal(DataGridImp.Rows[i].Cells["L.Balance"].Value) / 100000; } } MessageBox.Show(sum.ToString("#.##"), "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);Or you can try this:
decimal sum = DataGridImp.Rows.Cast() .Where(row => row.Cells["L.AC_No"].Value != null) .Where(row => { string cellValue = row.Cells["L.AC_No"].Value.ToString(); return cellValue == "90100000010" || cellValue == "90100000012" || cellValue == "90100000015" || cellValue == "90100000009"; }) .Sum(row => Convert.ToDecimal(row.Cells["L.Balance"].Value) / 100000); MessageBox.Show(sum.ToString("#.##"), "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);Amit MohantyRank #112 · 20K reputationPosted Jun 28, 2023, 6:27 AM EDT
decimal sum = 0; for (int i = 0; i < DataGridImp.Rows.Count - 1; i++) { if (DataGridImp.Rows[i].Cells["L.AC_No"].Value != null && DataGridImp.Rows[i].Cells["L.AC_No"].Value.ToString() == "90100000010") { sum += Convert.ToDecimal(DataGridImp.Rows[i].Cells["L.Balance"].Value) / 100000; } } MessageBox.Show(sum.ToString("#.##"), "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);Debashish Mahonta146 reputationPosted Jun 28, 2023, 6:57 AM EDT
How can i add multiple condition? Like
DataGridImp.Rows[i].Cells["L.AC_No"].Value.ToString() == "90100000010","90100000012","90100000015","90100000009")