Bob Cave
2009-10-08 20:28:01 UTC
I would like to intercept keystrokes typed into the cells of a DataGridView
control to prevent non-numeric data from being entered in the cell. I have
derived a class from DataGridViewCell and implemented the OnKeyPress method,
but when I type into the cells, OnKeyPress is not being called. Here is the
code I am using:
// In the form constructor, I call the following code to set up a new
column in the grid.
DataGridViewNumericColumn columnX = new
DataGridViewNumericCellColumn("X");
m_dataGrid.Columns.Add(m_columnX);
public class DataGridViewNumericCell : DataGridViewTextBoxCell
{
protected override void OnKeyPress(KeyPressEventArgs e, int rowIndex)
{
// Logic to exclude non-numeric keystrokes goes here.
base.OnKeyPress(e, rowIndex);
}
}
public class DataGridViewNumericCellColumn : DataGridViewColumn
{
public DataGridViewNumericCellColumn(String colName)
{
this.CellTemplate = new DataGridViewNumericCell();
this.Name = colName;
this.Width = 125;
}
public DataGridViewNumericCellColumn()
{
this.CellTemplate = new DataGridViewNumericCell();
}
}
First, is this the best way to accomplish what I am trying to do? Second,
why doesn't the OnKeyPress() method get called?
Thanks,
Bob
control to prevent non-numeric data from being entered in the cell. I have
derived a class from DataGridViewCell and implemented the OnKeyPress method,
but when I type into the cells, OnKeyPress is not being called. Here is the
code I am using:
// In the form constructor, I call the following code to set up a new
column in the grid.
DataGridViewNumericColumn columnX = new
DataGridViewNumericCellColumn("X");
m_dataGrid.Columns.Add(m_columnX);
public class DataGridViewNumericCell : DataGridViewTextBoxCell
{
protected override void OnKeyPress(KeyPressEventArgs e, int rowIndex)
{
// Logic to exclude non-numeric keystrokes goes here.
base.OnKeyPress(e, rowIndex);
}
}
public class DataGridViewNumericCellColumn : DataGridViewColumn
{
public DataGridViewNumericCellColumn(String colName)
{
this.CellTemplate = new DataGridViewNumericCell();
this.Name = colName;
this.Width = 125;
}
public DataGridViewNumericCellColumn()
{
this.CellTemplate = new DataGridViewNumericCell();
}
}
First, is this the best way to accomplish what I am trying to do? Second,
why doesn't the OnKeyPress() method get called?
Thanks,
Bob