2013-11-27 35 views
0

我有以下代碼:事件LostFocus製作datagridcell返回以前輸入的值

if (GridSellProducts.CurrentCell.ColumnIndex == 1 && e.Control is TextBox) 
{ 
    TextBox textBox = e.Control as TextBox; 
    textBox.KeyPress -= new KeyPressEventHandler(QuantityFieldValidate); 
    textBox.KeyPress += new KeyPressEventHandler(QuantityFieldValidate); 
    textBox.LostFocus -= new EventHandler(QuantityCellLeave); 
    textBox.LostFocus += new EventHandler(QuantityCellLeave); 
} 

private void QuantityCellLeave(object sender, EventArgs e) 
{ 
    // calculate total value 
    quantity = Convert.ToDecimal(GridSellProducts.Rows[GridSellProducts.CurrentCell.RowIndex].Cells["Qnty"].Value); 
} 

的問題是,當我運行的第一次的代碼,我輸入數量在Qnty字段中,無論輸入什麼數字,小數點quantity都會返回0,例如18.當我點擊單元格輸入另一個數字時,例如23,小數點現在返回數字18. 這是爲什麼?

回答

1

你只需要消費一個不同的事件; CellEndEdit

void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{ 
    if (e.ColumnIndex != qntyColumnIndex) { return; } 

    quantity = Convert.ToDecimal(
     GridSellProducts.Rows[e.RowIndex] 
         .Cells["Qnty"].Value); 

} 

其中qntyColumnIndex是該列的索引。

+0

謝謝邁克爾。你是對的。 –

+0

@KinyanjuiKamau,我很高興我能幫上忙! –