How to use for loop to sum items - c#

I am trying to calculate the total price of items after adding them to a combo box from a list box. In the list box I have both the type of item and ts price. I want to see the total price to increase as I add each item (click addButton) to the combo box. But what i am seeing is that the item is added to the combo box but I see only individual item prices instead of the sum of the prices. Here is a sample of my code.
private void addButton_Click(object sender, EventArgs e)
{
decimal price; // variables to holds the price
decimal total = 0; // variables to hold the total
int counter;
for (counter=0; counter <= 5; counter++)
{
price = decimal.Parse(priceLabel2.Text);
// add items price
total += price;
// display the total amount
costLabel.Text = total.ToString("c");
}
Any help would be appreciated,

Change:
private void addButton_Click(object sender, EventArgs e)
{
decimal price; // variables to holds the price
decimal total = 0; // variables to hold the total
int counter;
for (counter=0; counter <= 5; counter++)
{
price = decimal.Parse(priceLabel2.Text);
// add items price
total += price;
// display the total amount
costLabel.Text = total.ToString("c");
}
to:
decimal total = 0; // variables to hold the total
private void addButton_Click(object sender, EventArgs e)
{
decimal price; // variables to holds the price
int counter;
for (counter = 0; counter <= 5; counter++)
{
price = decimal.Parse(priceLabel2.Text);
// add items price
total += price;
// display the total amount
costLabel.Text = total.ToString("c");
}
}
The important change here is moving the total variable outside the function. This means that the value is maintained between clicks. If you put it inside the function it is reset to 0 on every click (which is not what you wanted).

Related

Sum Amount from Datagridview with Other Textbox and Show it Automatically

Screenshot
Hi. I need help from you guy. How do I calculate or sum all the value into the last textbox. I put number in my picture just want to explain what I need here.
I put some amount to calculate GST and show it to Total Legal Fees textbox.
After number 1, I put temporarily amount just to put more than 1, so if I have other amount, I just click ADD button.
This Add button help me to show total amount from number 2. Example, if I got one fee $20 and other is fee is $30. So total is %50 and it show into Total Disbursement textbox.
This is the problem I got. How do I calculate all the Legal Fees Total and Disbursement Total and show it automatically on my Grand Total textbox?
Here my code for Add button.
private void btnAdd_Click(object sender, EventArgs e)
{
dgvDisList.ColumnCount = 2;
dgvDisList.Columns[0].HeaderText = "Category";
dgvDisList.Columns[1].HeaderText = "Amount";
string[] row = new string[] { cbDisCategory.Text, tbAmount.Text };
dgvDisList.Rows.Add(row);
// Sum Total dari GridView
int sum = 0;
for (int i = 0; i < dgvDisList.Rows.Count; ++i)
{
sum += Convert.ToInt32(dgvDisList.Rows[i].Cells[1].Value);
}
tbTotalDisbursement.Text = sum.ToString();
}
And here is my GST calculation
private void tbLegalFees_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(tbLegalFees.Text, "^(\\$??)(\\d+)(\\.??)(\\d*)"))
{
decimal exGST = tbLegalFees.Text.StartsWith("") ? decimal.Parse(tbLegalFees.Text) : decimal.Parse(tbLegalFees.Text);
decimal incGST = exGST * (decimal)0.6;
decimal GST = incGST + exGST;
tbLegalFees.Text = string.Format("{0:f2}", exGST);
tbGSTpercent.Text = string.Format("{0:f2}", incGST);
tbTotalLegalFees.Text = string.Format("{0:f2}", GST);
}
}

Loop to calculate organism growth

I am trying to make a loop that calculates number of organisms over time, but I am stuck on how to make the loop update. Do I need to put something outside the for loop to update the total organisms?
private void calculateButton_Click(object sender, EventArgs e)
{
//declare variables for number of days passed and population
double days;
double organisms;
double increaseDaily;
double total_organisms;
//declare the constants to be used
const int interval = 1;
const int start_days = 1;
//try parse to get amount of starting organisms
if (double.TryParse(organismTextBox.Text, out organisms))
{
//try parse to get the percent daily increase
if (double.TryParse(dailyIncreaseTextBox.Text, out increaseDaily))
{
//try parse to get the number of days passed
if (double.TryParse(daysMultiplyTextBox.Text, out days))
{
//for loop to count through the number of days
for (int i = 1; i <= days; i += interval)
{
//calculate the amount of organisms
total_organisms = (organisms * (increaseDaily / 100) + organisms);
//display the amount of organisms after an amount of time
listBox1.Items.Add("after " + i + " days, the amount of organisms is " + total_organisms);
}
Each loop, you are calculating the total_organisms as the sum of organisms plus some percent:
total_organisms = (organisms * (increaseDaily / 100) + organisms);
You are never changing the value of organisms, so total_organisms will be calculated as the same value each loop. You should just updated the value of organisms instead.
Also, you could reduce indentation in your code by changing each if statement to test for parse failure and bail out:
private void calculateButton_Click(object sender, EventArgs e)
{
//declare variables for number of days passed and population
double days;
double organisms;
double increaseDaily;
List<string> errors = new List<string>();
//declare the constants to be used
const int interval = 1;
const int start_days = 1;
//try parse to get amount of starting organisms
if (!double.TryParse(organismTextBox.Text, out organisms)) {
errors.Add("Organisms must be a valid number");
}
//try parse to get the percent daily increase
if (double.TryParse(dailyIncreaseTextBox.Text, out increaseDaily)) {
errors.Add("Daily increase must be a valid number");
}
//try parse to get the number of days passed
if (double.TryParse(daysMultiplyTextBox.Text, out days)) {
errors.Add("Number of days must be a valid number");
}
if (errors.Any()) {
// Display errors to user here (depending on your UI)
return;
}
//for loop to count through the number of days
for (int i = 1; i <= days; i += interval) {
//calculate the amount of organisms
organisms = (organisms * (increaseDaily / 100) + organisms);
//display the amount of organisms after an amount of time
listBox1.Items.Add(
"after " + i + " days, the amount of organisms is " + organisms);
}
}
If you want to keep adding to the total number of organisms:
total_organisms = total_organisms + (organisms * (increaseDaily / 100) + organisms);

How to Add the column values in the TextChanged event?

I have type the value in GridView column.
After enter some data into the GridView, I want it to calculate the sum of one particular column.
How can I achieve this?
If what you need is to display the sum of a particular column in a dataGridView, then this could help:
private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 5)
textBox9.Text = CellSum().ToString();
}
private double CellSum()
{
double sum = 0;
for (int i = 0; i < dataGridView2.Rows.Count; ++i)
{
double d = 0;
Double.TryParse(dataGridView2.Rows[i].Cells[5].Value.ToString(), out d);
sum += d;
}
return sum;
}
Some considerations to take:
Make sure the data you are summing is in numeric form. Therefore the column type needs to be an integer, double or float (but surely not an nvarchar or varchar). This will ensure that the program does not go into error state when summing the values.
In the code above, taken from another answer in StackOverflow, the values in that column were parsed to double, to allow decimal numbers, and not simply whole numbers.
The sum needs to be stored in a variable of type double. It is up to you then what to do with it: Whether you want to store it in another place in the database or show it to the user in a label.
you have to sum the Values at your TextchangedEvent ,so please try this
protected void txtintroId_TextChanged(object sender, EventArgs e)
{
float total= 0;
foreach (GridViewRow gridViewRow in gridView.Rows)
{
lbltotal = (Label)gridViewRow.FindControl("lbltotal");
float rowValue = 0;
if (float.TryParse(lbltotal.Text.Trim(), out rowValue))
total += rowValue;
}
GridView1.FooterRow.Cells[3].Text = total.ToString();
}

Progressive loop calculations

Ok. So I'm trying to have a program.. where the user enters his salary and then the program will calculate his salary for the next four years with a raise of 2.5% each year.
I feel like I have done this completely wrong, because my loop is only calculating one time.. its not even showing four salary's.. not to mention having them each raised 2.5% each time.
private void btnDisplay_Click(object sender, EventArgs e)
{
int count;
for (count = 1; count <= 4; count++)
{
decimal Raise;
decimal Salary;
decimal Sum;
decimal Total;
Raise = Convert.ToDecimal(0.025);
Salary = Convert.ToDecimal(txtSalary.Text);
Sum = Salary * Raise;
Total = Salary + Sum;
label2.Text = Total.ToString("c");
}
txtSalary is whatever the user entered salary is.
label2 is the display of the calculation.
---------------- UPDATE: I have updated the code with the final product. Thanks to everyone for helping out especially Patrick Hofman! You are the best.. I couldn't have done it without you. ------------------------
private void btnDisplay_Click(object sender, EventArgs e)
{
decimal salary = Convert.ToDecimal(txtSalary.Text);
decimal raise = 0.025m;
decimal previous = salary;
for (decimal year = 1; year <= 4; year++)
{
decimal sum = previous * (1 + raise);
previous = sum;
listBox1.Items.Add(sum.ToString("c"));
}
I think you should have something like this:
private void btnDisplay_Click(object sender, EventArgs e)
{
decimal salary = Convert.ToDecimal(txtSalary.Text);
decimal raise = 0.025m;
decimal total = 0;
decimal previous = salary;
listBox1.Items.Add("Start: {0:N2}", salary);
for (int year = 1; year <= 4; year++)
{
decimal sum = previous * (1 + raise);
previous = sum;
total += sum;
listBox1.Items.Add("Year {0}: {1:N2}", year, sum);
}
listBox1.Items.Add("Total: {0:N2}", total);
}
Note I made some changes to the variables. Some were moved to keep them over the for loop.
The steps:
Start with setting the start point (previous) to the salary.
For each year, multiply the previous year's salary with the raise percentage +1.
Set the previous and add that year's salary to the total.
Show the total in the label.
int count;
Salary = Convert.ToDecimal(txtSalary.Text);
for (count = 1; count <= 4; count++)
{
Salary *= 1.025m;
}
label2.Text = Salary.ToString("c");
You need to make sure you're retrieve the salary once at teh beginning and don't overwrite it till the end.
Problem 1: You are declaring the variables inside the forloop.so each time they are initialised with their default values.
Solution 1: inorder to retain their last assigned values you need to move the declaration of the variables outside the loop.
Problem 2: you are not able to see the results/changes as you are updating the label inside the for loop without any delay.so evatually you can only see the last calculated result.
Solution2: You need to either create 4 different labels to show the 4 different results or you need to wait for some time for updating the label results in each iteration by using timer functionality.
Try This: using LabelArray
Label[] lblSalaries = new Label[4];
private void CreateControls()
{
int x = 0, y = 10;
for (int i = 0; i < lblSalaries.Length;i++ )
{
lblSalaries[i] = new Label();
x += 60;
lblSalaries[i].Size = new System.Drawing.Size(50, 30);
lblSalaries[i].Location = new System.Drawing.Point(x,y);
Controls.Add(lblSalaries[i]);
}
}
private void btnDisplay_Click(object sender, EventArgs e)
{
int count;
decimal Raise;
decimal Salary;
decimal Sum;
decimal Total;
CreateControls();
for (count = 1; count <= 4; count++)
{
Raise = Convert.ToDecimal(0.025);
Salary = Convert.ToDecimal(txtSalary.Text);
Sum = Salary * Raise;
Total = Salary + Sum;
lblSalaries[count-1].Text = Total.ToString("c");
}
}

Datagridview Error:: Index was out of range. How I can Solve it?

I have this form application project. I upload a snap of the sales field. Two datagridview are there. Bottom datagirdview contain TAX details. Contain of bottom datagrid came from database except “Amount” column. Amount column value provided by user or auto calculated. I write a code. When I try to execute it shows a error. Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index. How Can I solve it??
Snap::
Here is the code:
private void dgvSalesFooterAdd_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
decimal Total = 0;
decimal a=Convert.ToDecimal(lblTotalAdd.Text);
for (int i = 0; i <dgvSalesFooterAdd.Rows.Count ; i++)
{
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
}
lblFinalTotalAdd.Text = Total.ToString();
}
[NOTE: Error on
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
this two lins.]
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a *(Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
it will throw an exception because you are reading the value of 4th column which is null, because cell_value changed worked once you leave the cell...
got throught this link it will give you a better picture..
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx
and try you code like this..
void dgvSalesFooterAdd_CurrentCellDirtyStateChanged(object sender,
EventArgs e)
{
if (dgvSalesFooterAdd.IsCurrentCellDirty)
{
dgvSalesFooterAdd.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dgvSalesFooterAdd_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
decimal Total = 0;
decimal a=Convert.ToDecimal(lblTotalAdd.Text);
for (int i = 0; i <dgvSalesFooterAdd.Rows.Count ; i++)
{
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
}
lblFinalTotalAdd.Text = Total.ToString();
}
The exception is thrown when it does not find the Row index in i. You will have to reduce the number of rows by 1. This will tell the loop to count only the rows filled by values. Change the line
int i = 0; i <dgvSalesFooterAdd.Rows.Count
to
int i = 0; i <dgvSalesFooterAdd.Rows.Count - 1
Complete block will look like this;
for (int i = 0; i <dgvSalesFooterAdd.Rows.Count - 1; i++)
{
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
}

Categories