Can-Ann

In the keypress event of the datagrid I would like to make sure that the only numerics 0 to 9 are entered,for column 3 only.

Can anyone show me how to do this, thanks in advance.

I am using VS 2005 c#



Re: Windows Forms Data Controls and Databinding Datagridview - Keypress

Rahul Saxena

//check for the third column

if(dgvGroupDetails.CurrentCell.ColumnIndex == 2)

{

//check if presses key is 0 to 9

if(e.KeyChar = "0 to 9")

{
//true

}

}

try above in the key press event





Re: Windows Forms Data Controls and Databinding Datagridview - Keypress

Can-Ann

Everyone -

I found this exmple that works well:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if ((int)(((System.Windows.Forms.DataGridView)(sender)).CurrentCell.ColumnIndex) == 1)
{
e.Control.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.TextboxNumeric_KeyPress);

}
}

private void TextboxNumeric_KeyPress(object sender, KeyPressEventArgs e)
{
Boolean nonNumberEntered;

nonNumberEntered = true;

if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8)
{
nonNumberEntered = false ;
}

if (nonNumberEntered == true)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true ;
}
else
{
e.Handled = false;
}

}





Re: Windows Forms Data Controls and Databinding Datagridview - Keypress

yazad_gandhi

The above solution is awsome and it helped me in my application.

But i prefered to use it the following way:

private 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);
}
}

So if You want to add any allowable value lets say a dot (.), just add a dot to the string.

And yes, you can definately delete the text box you added and rename the event, if u want to, to an appropriate name.






Re: Windows Forms Data Controls and Databinding Datagridview - Keypress

Can-Ann

This works great - except it works for all columns on the datagrid, can I be missing something here