事件仅在第二次触发

时间:2013-03-20 16:16:33

标签: c# winforms gridview event-handling keydown

在gridview中有一个文本框类型列'Qty',它必须只接受数字。foll。代码工作正常,但只能从第二个输入。我只想在这里使用keydown。

private void GridViewSale_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{     
  if (GridViewSale.CurrentCell.ColumnIndex == 4) //Allow only numbers for QTY column
    {
      TextBox Qty = e.Control as TextBox;
      Qty.KeyDown += new KeyEventHandler(Qty_KeyDown);
    }
}
void Qty_KeyDown(object sender, KeyEventArgs e)
{         
  if ((e.KeyValue >= 48 && e.KeyValue <= 57) || (e.KeyValue >= 96 && e.KeyValue <= 105)//Allows numerics
    e.SuppressKeyPress = false;
  else
    e.SuppressKeyPress = true;           
  }

1.我应该在某个地方调用事件处理程序,比如form_load ..,以便为每个输入工作吗? 2.如果我必须禁用修改器输入(SHIFT + 1,SHIFT + 2),我应该如何编码?

1 个答案:

答案 0 :(得分:0)

找到这种行为的原因:第一次任何keydown(char,num或symbol)直接转到'EditingControlShowing'方法而不是'KeyDown'。所以输入已经被采用,因此问题。我用foll解决了这个问题。解决方法。 (将KeyDown替换为PreviewKeyDown并添加CellBeginEdit,以在单元格进入编辑模式之前检查键值:

private void GridViewSale_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
  {
    if (GridViewSale.CurrentCell.ColumnIndex == 4)//Allow only nums for QTY col.
          {
              TextBox Qty = e.Control as TextBox;
              Qty.KeyDown -= OnlyNums_KeyDown;
              Qty.KeyDown += OnlyNums_KeyDown;
          }
  }
private void GridViewSale_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
  {
     if ((e.KeyValue >= 48 && e.KeyValue <= 57) || (e.KeyValue >= 96 && e.KeyValue <= 105))
          {
              //Do Nothing
          }
          else
          {
              cancelEdit = true;
              GridViewSale.CellBeginEdit -= GridViewSale_CellBeginEdit;
              GridViewSale.CellBeginEdit += GridViewSale_CellBeginEdit;
          }
      }
private void GridViewSale_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
  {
      if (cancelEdit == true)
      {
          e.Cancel = true;
          cancelEdit = false;
      }
  } 

[我的第二个问题仍然没有答案]。