我想在DataGridView中的10個人之間劃分30個整個蘋果。
DataGridView位於KeyPreview設置爲true的窗體中。人員名稱顯示在設置爲只讀的DataGridViewTextBoxColumn(Column1)中。然後整數將被輸入到一個空的DataGridViewTextBoxColumn(Column2)。 當一個鍵被釋放時,總和被計算/重新計算,並且如果column2的總和爲30,那麼表單OK按鈕被啓用(其他被禁用)。KeyPress事件塊DataGridView中的KeyUp事件.net
問題是關於keyEvents。如果綁定KeyPress事件,則不會觸發KeyUp。
// Bind events to DataGridViewCell
private void m_DataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control != null)
{
e.Control.KeyUp -= m_DataGridView_KeyUp;
e.Control.KeyPress -= m_DataGridView_KeyPress;
e.Control.KeyUp += m_DataGridView_KeyUp;
e.Control.KeyPress += m_DataGridView_KeyPress;
}
}
//Only accept numbers
private void m_GridView_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8)
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
// Sum the apples in column2
private void m_DataGridView_KeyUp(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1 && e.RowIndex > 0)
{
int count = 0;
int parser = 0;
foreach (DataGridViewRow item in this.m_DataGridView.Rows)
{
if (item.Cells[1].Value != null)
{
int.TryParse(item.Cells[1].Value.ToString(), out parser);
count += parser;
}
}
//make the ok button enabled
m_buttonDividedApplen.Enabled = (count == 30);
}
}
這個故事問題變得陌生和陌生。如果我切換單元格,那麼觸發按鍵事件。有時鍵盤會觸發一次。
KeyUp並不總是或只有在按鍵處理時才執行? – gbianchi
只有在未附加KeyPress的情況下才執行KeyUp。 –