【发布时间】:2012-05-09 11:38:14
【问题描述】:
我想在 DataGridView 中将 30 个完整的苹果分配给 10 个人。
DataGridView 位于将 KeyPreview 设置为 true 的表单中。人员的姓名显示在设置为只读的 DataGridViewTextBoxColumn(Column1) 中。然后将整数输入到空的 DataGridViewTextBoxColumn(Column2) 中。
当一个键被释放时,总和被计算/重新计算,如果 column2 的总和为 30,则启用表单 OK 按钮(else disabled)。
问题在于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 事件。有时 keyup 会触发一次。
【问题讨论】:
-
KeyUp 不总是执行,还是仅在您在按键时处理它时执行?
-
KeyUp 仅在未附加 KeyPress 时执行。
标签: .net winforms datagridview c#-3.0 keyboard-events