Home All Groups Group Topic Archive Search About

Implementing a DataGridView numeric only column

Author
26 May 2006 5:25 PM
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.

Author
27 May 2006 11:21 AM
Chris Jobson
"Greg" <gregwilliams***@yahoo.co.uk> wrote in message
news:1148664335.339007.265260@38g2000cwa.googlegroups.com...
> 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
Author
30 May 2006 9:11 AM
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

AddThis Social Bookmark Button