1

在必须只接受数字的网格视图中有一个文本框类型列“数量”。如下所示。代码运行良好,但仅来自第二个输入。我只想在这里使用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),我应该如何在此处编码?

4

1 回答 1

0

找到了这种行为的原因:任何 keydown(char、num 或符号)第一次直接进入 'EditingControlShowing' 方法而不是 'KeyDown'。所以输入已经被采用,因此问题。我解决了这个问题。解决方法。(将 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;
      }
  } 

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

于 2013-03-25T06:32:01.563 回答