![](/img/trans.png)
[英]Siverlight: DataGridView adding items and getting selected items
[英]Getting the selected rows' values in datagridview and adding them up
我正在申請預訂winsform。 當用戶選擇任意數量的行時,每一行都將包含一列稱為“租金價格”的列。 然后,將獲得該單元格的值(稱為“租金”),並將其加起來並顯示在總成本標簽文本中。 但是問題是總成本沒有顯示。 這是我的代碼:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.