Alfonsus Dhani Alfonsus Dhani - 8 days ago 6
C# Question

Sum Integer and Show The Result to TextBox using C#

I got some problem when summing integer and show the result to

TextBox
using C#. When I run my code, the result that is shown just the result of
lim30den50tot
. I want to sum
lim30den50tot
,
lim60den50tot
, etc. How can I do that ?

private int lim30den50tot;
private int lim60den50tot;
private int lim150den50tot;
private int lim450den50tot;
private int lim600den50tot;


private void JumlahLembar()
{
int lim30 = 0;
int lim60 = 0;
int lim150 = 0;
int lim450 = 0;
int lim600 = 0;

foreach(DataGridViewRow row in JadwalisiGV.Rows)
{

if (!row.IsNewRow)
{


OleDbConnection kon = new OleDbConnection(koneksi);
OleDbCommand command = kon.CreateCommand();

kon.Open();
command.CommandText = "select * from [StokLembar$] where [Limit] = " + row.Cells["Limit"].Value;
OleDbDataReader reader = command.ExecuteReader();

while (reader.Read())
{
int den50 = int.Parse(reader["Lembar Denom 50"].ToString());
int den100 = int.Parse(reader["Lembar Denom 100"].ToString());

if (row.Cells["Limit"].Value.ToString() == "30")
{
lim30++;
lim30den50tot = lim30 * 2 * den50 * 50000;
}

else if (row.Cells["Limit"].Value.ToString() == "60")
{
lim60++;
lim60den50tot = lim60 * 2 * den50 * 50000;
}

else if (row.Cells["Limit"].Value.ToString() == "150")
{
lim150++;
lim150den50tot = lim150 * 2 * den50 * 50000;
}

else if (row.Cells["Limit"].Value.ToString() == "450")
{
lim450++;
lim450den50tot = lim450 * 2 * den50 * 50000;
}

else if (row.Cells["Limit"].Value.ToString() == "600")
{
lim600++;
lim600den50tot = lim600 * 2 * den50 * 50000;
}


TotalDen50Box.Text = (lim30den50tot + lim600den50tot + lim150den50tot + lim450den50tot + lim600den50tot).ToString();
}
kon.Close();
}
}
}

Answer

Put TotalDen50Box.Text outside your loop because you are overwrite it in every iteration of the loop. Also your integer value should be sum from current value plus previous one, if you want to show the sum for all rows. Example lim30den50tot += lim30 * 2 * den50 * 50000;

while(reader.Read())
{
    //stuff

    if(condition)
    {
        lim30den50tot += lim30 * 2 * den50 * 50000;
    }
    else if(condition2)
         //do the same for other ints
}

TotalDen50Box.Text = (lim30den50tot + lim600den50tot + lim150den50tot + lim450den50tot + lim600den50tot).ToString();