DataGridViewで30個のリンゴ全体を10人に分割したいと思います。
DataGridViewは、KeyPreviewがtrueに設定されているフォームにあります。人々の名前は、読み取り専用に設定されたDataGridViewTextBoxColumn(Column1)に表示されます。次に、整数は空のDataGridViewTextBoxColumn(Column2)に入力されます。キーを離すと、合計が計算/再計算され、column2の合計が30の場合、フォームの[OK]ボタンが有効になります(それ以外の場合は無効になります)。
問題は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);
}
}
この文章題はますます見知らぬ人になります。セルを切り替えると、キーアップイベントがトリガーされます。キーアップがトリガーされるのは1回だけです。