I am a beginner programmer and I am trying to modify the following code in order to allow only {'delete' , 'backspace' , one '.' , one '-' sign in the beginning of input , numbers '0 to 9'} on a textbox C#/winforms:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
(e.KeyChar != '.'))
{
e.Handled = true;
}
// only allow one decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
any help please?
CodePudding user response:
The question is very similar to this one except you have the added requirement of allowing -
So try this
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)) //bypass control keys
{
int dashIndex = textBox1.Text.IndexOf('-');
int dotIndex = textBox1.Text.IndexOf('.');
int selectionStart = textBox1.SelectionStart;
int selectionEnd = selectionStart textBox1.SelectionLength;
if (char.IsDigit(e.KeyChar))
{
if (dashIndex == 0 && selectionStart == 0 && selectionEnd == 0)
e.Handled = true;
}
else if (e.KeyChar == '-')
{
if (dashIndex == -1)
{
if (selectionStart != 0)
e.Handled = true;
}
else
e.Handled = !(selectionStart <= dashIndex && selectionEnd > dashIndex);
}
else if (e.KeyChar == '.')
{
if (dotIndex == -1)
e.Handled = false;
else
e.Handled = !(selectionStart <= dotIndex && selectionEnd > dotIndex);
}
else
e.Handled = true;
}
}
CodePudding user response:
It seems to me that you want to enable the operator to edit a possibly negative number with exactly one decimal point.
Your proposal is to check every input character as soon as it is typed, and allow or forbid the character. This gives a rather clumsy user interface.
- Operator types 9876
- Oh no, this is the incorrect number, I need -76"
- The operator uses the arrow keys to go back to before the 7, type the minus sign (intermediate: 98-76), use the arrow key to go one to the left, and delete delete to remove the 98 (intermediate: 9-76, -76)
Copy paste other values "Price €76.12" and remove unwanted characters (76.12) is impossible.
The proper interface would be, to allow the operator everything, until he signals you that he finished editing the number. Usually this is an OK button, or if you want the enter button. Subscribe to the proper event, and handle the input only then:
public void OnButtonOk_Clicked(object sender, ...)
{
string inputText = this.textBox1.Text;
this.ProcessInput(inputText);
}
// or if you want: react on enter:
public void OnKeyPress(object sender, ...)
{
// check if enter
bool enterPressed = ...
if (enterPressed)
{
this.ProcessInput(this.textBox1.Text);
}
}
public void ProcessInput(string inputText)
{
// check if the text can be converted to a double:
if (double.TryParse(inputText, double result))
{
// text ok: do what you need to do
}
else
{
// text not ok: warn the operator
}
}