有一个文本框类型列'Qty',在gridview中,只能接受数字。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),我应该如何在这里编写?
找到了这种行为的原因:任何keydown(char,num或symbol)第一次直接去' editingcontrolshow '方法而不是' 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;
}
}
[我的第二个问题仍然没有答案]。