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.