c# - 在 datagridview 中获取选定行的值并将它们相加

标签 c# winforms datagridview label

enter image description here

我现在正在制作预订 winsform 应用程序。当用户选择任意数量的行时,每行下面都会有一个名为 rental price 的列。然后将获取名为租金价格的列下的该单元格的值,并将其加起来并显示到总成本标签文本中。但问题是总成本未显示。这是我的代码:

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);
}

最佳答案

是的,错误在于循环,截至目前,您正在迭代 SelectedRows 中的行,并通过使用内部循环再次遍历每行的单元格,但取值与实际的网格而不是单元格。您可以使这变得简单,因为您想要遍历选定的行并且需要对每行中的 .Cells[4] 的值求和。为此你必须做这样的事情:

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();

关于c# - 在 datagridview 中获取选定行的值并将它们相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421953/

相关文章:

c# - 您使用什么 resharper 5 模式?

c# - 在窗口窗体节点下添加部分窗体类

winforms - 删除 listView 项目时崩溃?

C# - 如何使用单击按钮将数据从 dataGridView1 传递到另一个?

database - vb.net - 具有 BindingSource 和不同 DataSource 的 ComboBox

c# - ElasticSearch & Nest - 错误的转换

c# - 将 session 转换为 int 以进行 linq 查询

c# - 有关 Windows 窗体中选项卡的帮助

C# 将 DataGridView 中的更改提交到 DataTable

c# - 向面板添加垂直滚动条