[英]How to Trigger DataGridView CellEndEdit When A Cell Value Changes Programmatically
[英]How to trigger a calculation when any datagridview cell gets updated
我已經創建了要在單擊按鈕時觸發的計算,它將乘以2個datagridview列並在第三個列中顯示結果,然后將2列的總和求和並將結果發送到2個文本框中
現在,無論何時將值輸入到datagridview或對其進行編輯(列之一是產品數量),我都想實現這一點,因此在輸入值時應重做計算...因此應將此代碼添加到哪個void中?
private void btnClearPN_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
decimal a = Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
decimal b = Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value);
decimal c = a * b;
dataGridView1.Rows[i].Cells[4].Value = c.ToString();
}
GrandTotal();
Qty();
}
第一個選項-用戶完成編輯后更新單元格值
如果要在用戶完成值編輯后更新DataGridView,則應該處理DataGridView的CellEndEdit
事件(這由用戶移至下一個單元格或移至表單上的另一個控件來確定)。 有關更多信息,請參考MSDN-DataGridView.CellEndEdit事件 。
在當前所選單元格的編輯模式停止時發生。
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs dataGridViewCellEventArgs)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
decimal a = Convert.ToDecimal(dataGridView1.Rows[i].Cells[2].Value);
decimal b = Convert.ToDecimal(dataGridView1.Rows[i].Cells[3].Value);
decimal c = a * b;
dataGridView1.Rows[i].Cells[4].Value = c.ToString();
}
GrandTotal();
Qty();
}
第二種選擇-在用戶鍵入內容時更新單元格值
使用此方法會涉及更多點,並且需要正確處理EditControlShowing
事件,而對於TextBox
則是TextChanged
事件。
如果要在用戶鍵入時更新DataGridView,則應處理DataGridView的EditControlShowing
事件。 此事件將使您可以訪問編輯控件。 對於簡單的DataGridView設置,這是一個TextBox。 盡管這很容易是ComboBox,CheckBox或任何其他控件。
有關更多信息,請參考MSDN-DataGridView.EditingControlShowing事件 。
在顯示用於編輯單元格的控件時發生。
private DataGridViewRow CurrentRow;
private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs dataGridViewEditingControlShowingEventArgs)
{
CurrentRow = dataGridView1.CurrentRow;
TextBox textBox = dataGridViewEditingControlShowingEventArgs.Control as TextBox;
if (textBox != null)
{
textBox.TextChanged -= textBox_TextChanged;
textBox.TextChanged += textBox_TextChanged;
}
}
private void textBox_TextChanged(object sender, EventArgs eventArgs)
{
TextBox textBox = (TextBox)sender;
decimal a = Convert.ToDecimal(CurrentRow.Cells[2].Value);
decimal b = Convert.ToDecimal(CurrentRow.Cells[3].Value);
decimal c = a * b;
CurrentRow.Cells[4].Value = c.ToString();
}
注意:必須包括以下行:
textBox.TextChanged -= textBox_TextChanged;
隨着在運行時添加處理程序,每次顯示“編輯控件”時,都必須刪除任何以前添加的處理程序,否則它將被多次調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.