1

我有一個GridView(訂單)有三列:如何乘數據的GridView兩列,並顯示在另一列結果

  1. 價格
  2. 數量

我想要將PriceQuantity相乘,並在dataGridview的Total列中顯示結果。

請記住:我的dataGridview沒有綁定任何表。

我想這個代碼來實現我的目標,但沒有被退回,這是不工作的手段價值:

private void totalcal() 
{ 
    // is the foreach condition true? Remember my gridview isn't bound to any tbl 
    foreach (DataGridViewRow row in gvSale.Rows) 
    { 
     int a = Convert.ToInt32(row.Cells[3].Value) *  Convert.ToInt32(row.Cells[4].Value); // value is null why?? 
     row.Cells[5].Value = a; 
    } 
} 

這是我點擊一個按鈕調用方法。 (這是不工作原因在我的代碼裏面定義)

而且我想知道哪個是適合此計算的Datagridview事件?我不想來計算按鈕,點擊總量

回答

1

嘗試

int.Parse(row.Cells[3].Value.toString()) * int.Parse(row.Cells[4].Value.toString()) 

insted的的

Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[4].Value) 

而且你知道你可以隨時調用這個方法,如果你不希望它是點擊按鈕。在gvSale的行填充操作完成後調用它。

編輯

我猜你想在用戶進入價格Quanitity做計算。爲此,您需要爲您的datagridview編寫EditingControlShowing方法。這是一段代碼。我測試它實際上並得到它的工作。

在主類定義添加該代碼後InitializeComponent();

gvSale.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.gvSale_EditingControlShowing); 

然後添加這個方法:

TextBox tb = new TextBox(); // this is just a textbox to use in editing control 
int Price_Index = 3; // set this to your Price Column Index 
int Quantity_Index = 4; // set this to your Quantity Column Index 
int Total_Index = 5; // set this to your Total Column Index 

private void gvSale_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
{ 
    if (gvSale.CurrentCell.ColumnIndex == Price_Index || gvSale.CurrentCell.ColumnIndex == Quantity_Index) 
    { 
    tb = e.Control as TextBox; 
    tb.KeyUp += new KeyEventHandler(Calculate_Total); 
    } 
} 

private void Calculate_Total(object sender, KeyEventArgs e) 
{ 
    int Price_Value = 0; 
    int Quantity_Value = 0; 
    int.TryParse(gvSale.CurrentCell.ColumnIndex != Price_Index ? gvSale.CurrentRow.Cells[Price_Index].Value.ToString() : tb.Text, out Price_Value); 
    int.TryParse(gvSale.CurrentCell.ColumnIndex != Quantity_Index ? gvSale.CurrentRow.Cells[Quantity_Index].Value.ToString() : tb.Text, out Quantity_Value); 
    gvSale.CurrentRow.Cells[Total_Index].Value = Price_Value * Quantity_Value; 
} 
+0

還是空不工作 –

+0

你確定你的_Price_列索引是3和_數量_列索引是4? –

+0

是的,你有沒有錯誤的感謝,但行填充行gridview我沒有找到什麼是適當的事件 –

相關問題