There is a solution here that allows either a numerical value with only a minus sign or a decimal sign with a minus sign and a decimal point. Most of the previous answers did not take into account the selected text. If you change the ShortcutsEnabled text box to false, you also cannot insert garbage into the text box (it disables right-clicking). Some solutions allowed you to enter data up to a minus. Please make sure I catch everything!
private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e)
{
if (numeric)
{
if (txt.Text == "" || txt.SelectionStart == 0)
{
if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
return false;
else
return true;
}
else
{
if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back))
return false;
else
return true;
}
}
else
{
if (txt.Text == "" || txt.SelectionStart == 0)
{
if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
return false;
else
{
if ((e.KeyChar == '.' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains(".") || txt.SelectedText.Contains(".")))
return false;
else
return true;
}
}
else
{
if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back) || (e.KeyChar == '.' && (!txt.Text.Contains(".") || txt.SelectedText.Contains("."))))
return false;
else
return true;
}
}
}
source
share