Reputation: 1
I would like to validate that a DataGridView column only accepts integers.
I used the Keypress
event, but this event was not fired on pressing a key.
Here's the code I used
private void dgvSaleReturnWintoutInvoice_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(dgvSaleReturnWintoutInvoice_KeyPress);
if (dgvSaleReturnWintoutInvoice.Columns["dgvReturnQTY"].Index == dgvReturnQTY.Index)
{
TextBox tbt = e.Control as TextBox;
if (tbt != null)
{
tbt.KeyPress += new KeyPressEventHandler(dgvSaleReturnWintoutInvoice_KeyPress);
}
}
}
private void dgvSaleReturnWintoutInvoice_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
Upvotes: 0
Views: 289
Reputation: 74720
Your code works for me, though the way I detected the current column differs:
if (someDataGridView.CurrentCell.OwningColumn == someDataGridView.Columns["someColumn"])
I would also point out that your code doesn't prevent someone pasting alpha text into the box
Upvotes: 1