3

I have a datagridview on the form. and there are 4 columns in the grid - No, Answer, Key, Result. No, Key and Result Columns are read only. it means that i'm not going to enter some data to these columns. But i will enter values to Answer column. And values can be only - A, B, C, D and E. when i press for example X key i dont want X to be show in the cell. i can do it with textbox's with keypress event.

now can you tell me, how can i use keypress event of Answer columns cell event to realize it.

Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
namco
  • 6,208
  • 20
  • 59
  • 83

1 Answers1

3

You can use the EditingControlShowing event of the DataGridView to accomplish this.

In the eventhandler of this event, you have access to the Textbox that 's being displayed whenever you enter data inside the datagrid.
This means, that at this point, you can attach an eventhandler to the KeyPress event of the textbox that is displayed:

        private bool _firstTime = true;

        private void dataGridView1_EditingControlShowing( object sender, DataGridViewEditingControlShowingEventArgs e )
        {
            if( !_firstTime )
            {
                return;
            }

            _firstTime = false;

            var t = e.Control as TextBox;

            if( t != null )
            {
                t.KeyPress += OnKeyPress;
            }
        }

        private void OnKeyPress( object sender, KeyPressEventArgs e )
        {
            if( e.KeyChar != 'A' && e.KeyChar != 'B' && e.KeyChar != 'C' )
            {
                e.Handled = true;
            }
        }

Since the DataGridView will always 'share' the textbox control for every cell in the grid that uses textboxes, you should check whether it is the first time that the event is raised.
If you have other columns in the DataGridView which are not readonly, and where you want the user to enter data as well, which is not constrained, then this approach won't be that suitable. (Unless you check in the OnKeyPress eventhandler to which column the current cell belongs).

(Note that you'll have to consider the lowercase a, b, c as well.

Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154