Implementing a DataGridView numeric only column

G

Greg

I'm new to the datagridview control, and am left wondering how one goes
about restricting input to numeric only. Is it possible to trap key
presses at the cell level, and in the relevant columns, ignore them if
non-numeric?

Greg.
 
C

Chris Jobson

Greg said:
I'm new to the datagridview control, and am left wondering how one goes
about restricting input to numeric only. Is it possible to trap key
presses at the cell level, and in the relevant columns, ignore them if
non-numeric?

If you handle the EditingControlShowing event you can access the actual
control used for editing (a class derived from TextBox for a
DataGridViewTextBoxColumn) and hook up to the events of that control. The
following code shows how to restrict input to numbers in column 3.

private void itemDataGridView_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (itemDataGridView.CurrentCell.ColumnIndex == 3)
{
TextBox txtEdit = e.Control as TextBox;
txtEdit.KeyPress += new
KeyPressEventHandler(txtEdit_KeyPress);
}
}

void txtEdit_KeyPress(object sender, KeyPressEventArgs e)
{
if ("0123456789\b".IndexOf(e.KeyChar) == -1)
e.Handled = true;
}

Chris Jobson
 
G

Greg

Thats great Chris, just what I was looking for.

Incidentally, the check for the column number in EditingControlShowing
did not prevent the key press event for columns that I didnt want to be
tested. I got it to work by putting the check for column number in the
key press. Not sure why it was like this, but its working anyway!

Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top