簡體   English   中英

datagridview乘以單元格值

[英]datagridview multiplying cell value

我對DataGridView有問題。 我想將兩個單元格相乘並將結果顯示在第三個單元格中。

我有兩個DataGridView 第一個DataGridView從數據庫獲取數據。 在我從第一個DataGridView選擇行並將第二行添加到第二個DataGridView之后,第二個DataGridView獲取值。 列A從第一個DataGridView獲取(從數據庫獲取); 用戶在B列中手動插入值。

example of second datagridview: 
Price |  Amount  |  Total
10.50 | 2        | 21.00
5.20  | 4        | 20.80
7.30  | 5        | 36.50

之后,我想對C列求和,並在文本框中顯示總和。

A列是十進制類型; B列是整數; C列也應為十進制。

這是一個人在互聯網上給我的解決方案,但它僅適用於手動獲取數據的DataGridView ,如果數據來自數據庫則不起作用:

decimal sum = 0.0m;

for (int i = 0; i < gridProizvodi.Rows.Count; i++)
{
    DataGridViewRow row = gridProizvodi.Rows[i];
    if (row.IsNewRow) break;
    decimal product = Convert.ToDecimal(row.Cells[1].Value)
                    * Convert.ToInt32(row.Cells[2].Value);

    sum += product;
    row.Cells[3].Value = product;
}

txtCijena.Text= sum.ToString();

我得到了一個argument out of range exception was unhandledargument out of range exception was unhandled此行中argument out of range exception was unhandled錯誤

decimal product = Convert.ToDecimal(row.Cells[1].Value)
                * Convert.ToInt32(row.Cells[2].Value);

有人可以幫我找到解決方案嗎?

我不確定您使用的是表單還是webapp ...以下選項通常適用於webapp,我對表單一無所知。

這通常在自動生成GridView列時發生,即gridview.AutoGenerateColumns = true; 它不知道有任何列,因此會給您一個out of range異常。 您需要將其設置為false並告訴它顯示哪些列。 在第三列的模板字段中,您可以簡單地將綁定屬性更改為乘數值。

另一個選擇是從數據庫返回三列,第三列是您的乘積值。

希望這可以幫助...

如果您因為悲傷而在線上發生錯誤。 然后,更快的解決方案是使用列名。 正如@Andres提到的,最好使用索引。

從表單設計器中檢查列名稱,然后像這樣使用:

decimal product = Convert.ToDecimal(row.Cells[datagridviewTextBoxColumn1.Name].Value)
                * Convert.ToInt32(row.Cells[datagridviewTextBoxColumn2.Name].Value);

或者更好的是使用列的自定義名稱。

您的第二個datargidview是否有預定義的列或以編程方式創建的?

如果它們具有預定義的名稱->然后使用它們

如果不是->那么,因為在第二個datagridview中總是有相同的列,那么最好在設計器中一次創建一個列

如果你這樣改變怎么辦

decimal sum = 0.0m;
decimal product = 0;

for (int i = 0; i < gridProizvodi.Rows.Count; i++)
{
    DataGridViewRow row = gridProizvodi.Rows[i];
    if (row.IsNewRow) break;
    product = row.item("Price") * row.item("Amount");
    '--- if your price and amount field is numeric type, you dont have to convert it

    sum += product;
    row.item("Total") = product;
}

如果要在VB.NET中執行此操作……

Dim sum As Decimal = 0D

For i As Integer = 0 To DataGridView1.Rows.Count - 1
    Dim row As DataGridViewRow = DataGridView1.Rows(i)
    If row.IsNewRow Then
        Exit For
    End If

    Dim product As Decimal = Convert.ToDecimal(row.Cells("Column1").Value) * _
            Convert.ToDecimal(row.Cells("Column2").Value)
    'sum += product
    row.Cells("Column3").Value = product
Next

謝謝!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM