簡體   English   中英

如何將datagridview中第三列的兩列數據相乘

[英]How to multiply data of two columns for third column in datagridview

我想將兩列的數據相乘並在第三列中顯示。

例如:

1st Column: Quantity
2nd Column: Rate
3rd Column: Price

當用戶在價格列中自動輸入數量和費率的數據時,我想乘以Quantity=2rate=50我希望出現100

同時,我想在用戶輸入數量和費率的數據時進行除法,例如Price=100rate=50自動在 Quantity 列中出現,我希望出現2

當用戶輸入數量和費率的數據時,例如Price=100Quantity=2自動在 Rate 列中,我希望出現50

這三個將發生在同一個 datagridview 中。 用戶只需輸入這三個中的任何兩個字段,第三個將自動出現。

使用C#、VS2008、SQL 2008

private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{ 
    int quantity,rate; 
    for (int i = 0; i < dataGridView2.Rows.Count; i++) 
    { 
        if(int.TryParse(dataGridView2.Rows[i].Cells[1].Value.ToString(), out quantity) && int.TryParse(dataGridView2.Rows[i].Cells[2].Value.ToString(), out rate)) 
        { 
             int price = quantity * rate; dataGridView2.Rows[i].Cells[3].Value = price.ToString(); 
        } 
    } 
}

我寫了這段代碼。 那里顯示一個錯誤。 Object 引用未設置為 object 的實例

if(int.TryParse(dataGridView2.Rows[i].Cells[1].Value.ToString(), out quantity) && int.TryParse(dataGridView2.Rows[i].Cells[2].Value.ToString(), out rate)) 

這條線。


在此處輸入圖像描述

我想這樣做。 用戶可以填寫這 3 個字段中的任意 2 個字段。第三個字段將自動填寫。

處理 gridview 的CellEndEdit事件。 在該事件中計算並將值分配給第三列

就像是

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        int quantity,rate;
        if (int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["quantity"].Value.ToString(), out quantity) && int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["rate"].Value.ToString(), out rate))
        {
            int price = quantity * rate;
            dataGridView1.Rows[e.RowIndex].Cells["price"].Value = price.ToString();
         }
    }

這是您的解決方案。

double s = Convert.ToDouble(DataGridShowAddedProducts.Rows[0].Cells[2].Value);
        double s1 = Convert.ToDouble(DataGridShowAddedProducts.Rows[0].Cells[2].Value);
        double s13 = s1 * s;
        MessageBox.Show(s13.ToString());
decimal s=0, s1=0,s13 = 0;
        for (int j = 0; j< dgvsaledetails.Rows.Count; ++j)
        {
            s = Convert.ToDecimal(dgvsaledetails.Rows[j].Cells[6].Value);
            s1 = Convert.ToDecimal(dgvsaledetails.Rows[j].Cells[10].Value);
            s13 = s * s1;
            dgvsaledetails.Rows[j].Cells["amount"].Value = s13.ToString();

        }

通常會看到錯誤參數列所以不要使用 header 列名,但僅用於列名,如

decimal qty = 0, price = 0, amount = 0;
for (int j = 0; j < dataGridView2.Rows.Count; ++j)
{
              // cloumn9=qty
  qty = Convert.ToDecimal(dataGridView2.Rows[j].Cells["Column9"].Value);
// column4 = price
  price = Convert.ToDecimal(dataGridView2.Rows[j].Cells["Column4"].Value);
  amount = qty * price;
// cloumn7 = amount
 dataGridView2.Rows[j].Cells["Column7"].Value = s13.ToString();

            }

暫無
暫無

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

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