简体   繁体   English

在datagridview中获取所选行的值并将其加起来

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

在此处输入图片说明

I am making a booking winsform application now. 我正在申请预订winsform。 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. 是的,这是循环中的错误。到目前为止,您正在迭代SelectedRows的行,并使用内部循环再次遍历每行的单元格,但要获取相对于实际网格而不是单元格的值。 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. 您可以简化此过程,因为您要遍历选定的行,并且需要对每行中的.Cells[4]值求和。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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