This works well but seems to work for all columns,
Can anyone correct or advise me - thanks.
void Numeric_KeyPress(object sender, KeyPressEventArgs e)
{
string str = "\b0123456789";
e.Handled = !(str.Contains(e.KeyChar.ToString()));
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if ((dataGridView1.CurrentCell.ColumnIndex) == 0)
{
e.Control.KeyPress += new KeyPressEventHandler(this.Numeric_KeyPress);
}
}

datagrid keypress handler
bird.tw
I think I solved the problem,
bo_dong
Hi,
You dont need to those two exact same method to process the events.
Try to code more elegantly such as
int i = currentTransactionsDataGridView.CurrentCell.ColumnIndex;
if ( i == 0 || i == 4)
{
e.Control.KeyPress += new KeyPressEventHandler(this.Numeric_KeyPress);
}
or
switch (currentTransactionsDataGridView.CurrentCell.ColumnIndex)
{
case 0:
case 4: e.Control.KeyPress += new KeyPressEventHandler(this.Numeric_KeyPress);
break;
default: break;
}
Thanks
kkennedy1008
Hi,
You meant it affected all the columns
As far as the code you displayed which I've tried, and it works normally (only affect first column)
Please check what else you've done with the datagridview.
Thank you
Mark Benningfield
Yes, it affected every column, as soon as you change column 1 or column 4 then all columns will only accept numerics.
Do I need to remove the handler for columns other than 1 or 4
here is the actual test code:
public partial class MyTest : Form{
public MyTest(){
InitializeComponent();
}
#region
Handlers void Numeric_KeyPress(object sender, KeyPressEventArgs e){
string str = "\b0123456789";e.Handled = !(str.Contains(e.KeyChar.ToString()));
}
void Amount_KeyPress(object sender, KeyPressEventArgs e){
string str = "\b0123456789.";e.Handled = !(str.Contains(e.KeyChar.ToString()));
}
#endregion
Handlers
private void MyTest_Load(object sender, EventArgs e){
// TODO: This line of code loads data into the '_2000GLDataSet.CurrentTransactions' table. You can move, or remove it, as needed. this.currentTransactionsTableAdapter.Fill(this._2000GLDataSet.CurrentTransactions);}
private void currentTransactionsDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e){
if ((this.currentTransactionsDataGridView .CurrentCell.ColumnIndex) == 1)e.Control.KeyPress +=
new KeyPressEventHandler(this.Numeric_KeyPress); if ((this.currentTransactionsDataGridView.CurrentCell.ColumnIndex) == 4)e.Control.KeyPress +=
new KeyPressEventHandler(this.Amount_KeyPress);}
}
McKears
Thanks for the pointer Fegi - but it doesnot solve the problem of this happening to all columns.