Getting a sum of added cells in an ultragridview
Your Concerns


  I was just wondering if you could help me write this code neater or more efficiently?


Efficiency

You are looping through the data twice. Once to calculate adjustedsum from column["PrevFY"] and once for column["BudgetAmt"]. In both cases, actualsum gets calculated exactly the same way. It seems you so badly wanted to reuse variables that you forgot you could have just looped through the rows and store data in multiple variables.

decimal actualsum = 0m;
decimal adjustedTotal = 0m;
decimal originalTotal = 0m;

for (int i = 0; i &lt; 2; i++)
{
    var row = dgvBudget.Rows[i];
    actualsum += Convert.ToDecimal(row.Cells["Actual_c"].Value);
}

for (int i = 3; i &lt; 12; i++)
{
    var row = dgvBudget.Rows[i];
    adjustedTotal += Convert.ToDecimal(row.Cells["PrevFY"].Value);
    originalTotal += Convert.ToDecimal(row.Cells["BudgetAmt"].Value);
}

nbrAdjustedTotal.Value = adjustedTotal + actualsum;
nbrOriginalTotal.Value = originalTotal + actualsum;




Compactness (neatness)

You have recurring decimal parsing from data cells:


Convert.ToDecimal(row.Cells["Actual_c"].Value)



You could make a utility method for this. I'm assuming the class for the data row is called Row.

private static decimal ParseDecimal(Row row, string columnName)
{
    return Convert.ToDecimal(row.Cells[columnName].Value);
}


Further refactored:

decimal actualsum = 0m;
decimal adjustedTotal = 0m;
decimal originalTotal = 0m;

for (int i = 0; i &lt; 2; i++)
{
    var row = dgvBudget.Rows[i];
    actualsum += ParseDecimal(row, "Actual_c");
}

for (int i = 3; i &lt; 12; i++)
{
    var row = dgvBudget.Rows[i];
    adjustedTotal += ParseDecimal(row, "PrevFY");
    originalTotal += ParseDecimal(row, "BudgetAmt");
}

nbrAdjustedTotal.Value = adjustedTotal + actualsum;
nbrOriginalTotal.Value = originalTotal + actualsum;


Proposed Result

We could make the code even more compact by using LINQ's Skip, Take and Sum extension methods. I don't have access to the code, but I'm sure you could do something like:

var rows = dgvBudget.Rows.Take(3);
var actualsum = rows.Select(row =&gt; ParseDecimal(row, "Actual_c")).Sum();
var rows = dgvBudget.Rows.Skip(3).Take(9);
var adjustedTotal = rows.Select(row =&gt; ParseDecimal(row, "PrevFY")).Sum();
var originalTotal = rows.Select(row =&gt; ParseDecimal(row, "BudgetAmt")).Sum();

nbrAdjustedTotal.Value = adjustedTotal + actualsum;
nbrOriginalTotal.Value = originalTotal + actualsum;


This does come with a slight performance penalty, since you loop the first 3 items twice (once to skip). But it comes at a good increase in readability and compactness.