Reputation: 3575
I have got this code which calculates the summary of 2 multiplied columns
of all rows in datagridview
and shows the result in textbox
.
I have got a third column called sum
in which I would like to show the particular result of each row. I'm sorry because I have no idea how can I do that, so I haven't tried anything yet. May you please show me the way?
Thanks everybody for your time,comments or answers.
private void vypocti_odvody(int price, int vat, int tot_rows2)
{
try
{
double outVal = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
outVal = outVal + (Convert.ToDouble(row.Cells[price].Value)/100) * Convert.ToDouble(row.Cells[vat].Value) + (Convert.ToDouble(row.Cells[price].Value));
}
// s_ub_celk.Text = (((a / 100) * b) + a).ToString();
Convert.ToDecimal ( result.Text = outVal.ToString()) ;
}
catch (Exception ex)
{
MessageBox.Show("Chybové hlášení K3 " + ex.Message.ToString());
}
}
Upvotes: 1
Views: 1178
Reputation: 581
datagridview has a property called columns from where you can see at which position your column "sum" is but for you the most simple thing would be:
row.Cells["sum"].Value=10;
Upvotes: 0
Reputation: 17590
Just modify your foreach
loop like this:
double outVal = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var sum = (Convert.ToDouble(row.Cells[price].Value)/100) * Convert.ToDouble(row.Cells[vat].Value) + (Convert.ToDouble(row.Cells[price].Value));
row.Cells["sum"].Value = sum;
outVal += sum;
}
you have to introduce new variable that will hold sum value of both cells to set it in the new cell and after that add it to total sum.
Upvotes: 1
Reputation: 7619
You can simply give the value to the column by assigning it's Value
property:
private void vypocti_odvody(int price, int vat, int tot_rows2)
{
try
{
double outVal = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
double localSum = (Convert.ToDouble(row.Cells[price].Value)/100) * Convert.ToDouble(row.Cells[vat].Value) + (Convert.ToDouble(row.Cells[price].Value));
outVal = outVal + localSum;
row.Cells[sumcolumn].Value = localSum;
}
Convert.ToDecimal ( result.Text = outVal.ToString()) ;
}
catch (Exception ex)
{
MessageBox.Show("Chybové hlášení K3 " + ex.Message.ToString());
}
}
Just substitute the sumcolumn
name.
Upvotes: 2