简体   繁体   中英

Getting the selected rows' values in datagridview and adding them up

在此处输入图片说明

I am making a booking winsform application now. When a user chooses any number of rows, there will be a column called rental price that each row is under. Then the value of this cell under the column called rental price will be gotten and add up and display to the total cost label text. But the problem is the total cost is not displaying. Here is my code:

private void Payment_Load(object sender, EventArgs e)
{
   NameOfUser.Text = UserAccounts[0].Name;
   EmailOfUser.Text = UserAccounts[0].Email;
   PaymentType.Text = UserAccounts[0].PaymentType;        
   double totalCost = 0;
   foreach (DataGridViewRow row in b1.DataGridView1.SelectedRows)
   {
        int index = 0;
        foreach (DataGridViewCell cell in row.Cells)
        {
            totalCost += (double)dataGridView1.Rows[index].Cells[4].Value;
        }
        index++; 
   }

   TotalCost.Text = Convert.ToString(totalCost);
}

Yes the Mistake is in the looping, As of now you are iterating the rows in the SelectedRows and by using the inner loop you again looping through the cells of each row But taking values with respect to the actual grid instead for the cell. You can make this simple as you wanted to iterate through the selected rows and need to sums the value of .Cells[4] in each row. for that you have to do something like this:

foreach (DataGridViewRow row in b1.DataGridView1.SelectedRows)
{
   string value = row.Cells[4].Value.ToString();
   double currentCellValue = 0.0;  
   if(double.TryParse(value , out currentCellValue)
   { 
      totalCost += currentCellValue;
   }
 }
TotalCost.Text = totalCost .ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM