I am working on Datagridview and I have multiple columns. Some columns must accept the only numeric value, some only accept a string only, and some columns accept a specific format like 0000-0000-0000. I used the below code:
private void adgUser_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (adgUser.CurrentCell.ColumnIndex == 0)
{
e.Control.KeyPress -= AllowLettersOnly;
e.Control.KeyPress += AllowLettersOnly;
}
if (adgUser.CurrentCell.ColumnIndex == 1)
{
e.Control.KeyPress -= AllowLettersOnly;
e.Control.KeyPress += AllowLettersOnly;
}
if (adgUser.CurrentCell.ColumnIndex == 2)
{
e.Control.KeyPress -= AllowNumbersOnly;
e.Control.KeyPress += AllowNumbersOnly;
}
}
private void AllowNumbersOnly(Object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
e.Handled = true;
}
private void AllowLettersOnly(Object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar))
e.Handled = true;
}
Now, this code is not working fine. I am inserting data through datagridview into the database table and make sure columns only accept valid format while inserting data. Please advise
I suspected you're not assigning KeyPress
handlers to the TexBox
control hidden inside the DataGrdivView
and looked around and found this solution, applied it to your example and it works as expected:
private void adgUser_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
TextBox txtEdit = e.Control;
txtEdit.MaxLength = 2;
// remove any existing handler
txtEdit.KeyPress -= txtdgvDiaryEdit_Keypress;
txtEdit.KeyPress += txtdgvDiaryEdit_Keypress;
}
private void txtdgvDiaryEdit_Keypress(object sender, Global.System.Windows.Forms.KeyPressEventArgs e)
{
// Test for numeric value or backspace
if (Information.IsNumeric(e.KeyChar.ToString()) | e.KeyChar == (char)Keys.Back)
{
e.Handled = false; // if numeric
}
else
{
e.Handled = true;
} // if non numeric
}
This only allows two digits. Obviously, you have to apply your constraints (numbers, letters, length,...), but the logic is what you're after, I believe.