Learnin2Code
Learnin2Code

Reputation: 121

Displaying data in the Data Grid View? Access, C#

I want to calculate the Total Price and display it in the Data Grid View. The fourth column does not retrieve information from the database, so I don't know how to do this. Here's what the GUI looks like:

enter image description here

Here's the code I have so far...

                double colTotal = 0; //set column total to 0

                foreach (DataRow currentRow in itemDS.Tables[0].Rows)
                {
                    // add to data grid view
                    invoiceDataGridView.Rows.Add(currentRow[1].ToString(), currentRow[2].ToString(), currentRow[3].ToString());

                    //Decalare variables for item quantity and price
                    var itemQuant = Convert.ToDouble(currentRow[1]);
                    var priceEach = Convert.ToDouble(currentRow[3]);

                    //Multiply the item quantity by the item price
                    double subTotal = itemQuant * priceEach;

                    //do this for each row
                    colTotal += subTotal;
                }

                //Display subtotal
                subTotalOutput.Text = colTotal.ToString();
                //Calculate tax
                double tax = colTotal * .073;
                //Display total tax
                taxOutput.Text = Convert.ToString(tax);
                //Add the subtotal and the total tax
                double totPrice = colTotal + tax;
                //Display total price
                totalOutput.Text = Convert.ToString(totPrice);

            }

Upvotes: 0

Views: 1442

Answers (2)

tobyb
tobyb

Reputation: 746

I believe you can just do the subTotal calculation before you populate the grid, and add the subTotal variable on the end to your call to dataGrid.Rows.Add(). Like so:

foreach (DataRow currentRow in itemDS.Tables[0].Rows)
{
    //Decalare variables for item quantity and price
    var itemQuant = Convert.ToDouble(currentRow[1]);
    var priceEach = Convert.ToDouble(currentRow[3]);

    //Multiply the item quantity by the item price
    double subTotal = itemQuant * priceEach;


    // add to data grid view
    invoiceDataGridView.Rows.Add(currentRow[1].ToString(), currentRow[2].ToString(), currentRow[3].ToString(), subTotal);

    //do this for each row
    colTotal += subTotal;
}

Upvotes: 1

Tyler Daniels
Tyler Daniels

Reputation: 633

I'll start by saying that you could make your life easier using the DataSource property of the DataGridView control, but to resolve your issue given your current setup, I would simply move some code around and do it like this:

double subTotal = itemQuant * priceEach;

invoiceDataGridView.Rows.Add(currentRow[1].ToString(), currentRow[2].ToString(), currentRow[3].ToString(), subTotal.ToString());

Upvotes: 0

Related Questions