I came across a problem where i have to fire the Key Press event for DataGrid. But Unforyunately the DataGridView does not conatin an event like 'CellKeyPress' to capture a cell's KeyPress event, since there are several kinds of cells, e.g. DataGridViewTextBoxCell, DataGridViewComboBoxCell,DataGridViewCheckBoxCell etc, and also not all DataGridView cells should have the 'KeyPress' event.
Instead there is an alternate event provided by DataGridView named "EditingControlShowing", which brings us the inner editing control the
current cell is holding. Hence we could get the editing control by handling the
EditingControlShowing event and then subscribe the KeyPress event of the
editing control.
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
TextBox txtbox = e.Control as TextBox;
if (txtbox != null)
{
txtbox.KeyPress += new KeyPressEventHandler(txtbox_KeyPress);
}
}
private void txtbox_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}
DataGridView Cells to accept only Integer Value
The following code checks the Datagrid Cells to accept only integer values.
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
TextBox txtbox = e.Control as TextBox;
if (txtbox != null)
{
//Event to fire up if the Control is a TextBox
txtbox.KeyPress += new KeyPressEventHandler(txtbox_KeyPress);
}
}
private void txtbox_KeyPress(object sender, KeyPressEventArgs e)
{
string str = "/b0123456789"; // Holds Integer Values
e.Handled = !(str.Contains(e.KeyChar.ToString()));
}
Remove Integer Validation for a Particular Cell in DataGrid
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
TextBox txtbox = e.Control as TextBox;
if (txtbox != null)
{
if ((dgrd.CurrentCell.ColumnIndex) == 1)
{
//Event to fire up if the Control is a TextBox & ColumIndex is 1.
txtbox.KeyPress += new KeyPressEventHandler(txtbox_KeyPress);
}
else
{
//Removes the event for the Control if the ColumIndex is not 1.
txtbox.KeyPress -= new KeyPressEventHandler(txtbox_KeyPress);
}
}
}
private void txtbox_KeyPress(object sender, KeyPressEventArgs e)
{
string str = "/b0123456789"; // Holds Integer Values
e.Handled = !(str.Contains(e.KeyChar.ToString()));
}
Monday, August 3, 2009
DataGridView Key Press Events
Labels: .net
Subscribe to:
Posts (Atom)