Hi, I'm somewhat new to C# and I've created a numbers (backspace, delete, negative, and decimal) only text box. However the way I'm testing whether to allow for negative numbers only allows them to be added if they are typed as the first character.
Below is in an if statement where if all the statements are false, it takes does not allow the key to be registered with the text box. Since below is the code I'm trying to use to allow only a single negative sign, and only in the first space. All well and good, but not so useful when I want to add a negative to a number I've already written.
(!((e.KeyChar == '-') && (textBox1.Text == "")))
Obviously this is a problem - so I'm wonder how you can check where the insertion point is (the vertical flashing line) in the text box so that I can check if it is the first character being entered!
Oh yes, and below is my entire code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) //important to note that this kind of event "KeyPress" Is nessecary for this kind of operation!
{
//My rather long numbers only textbox if statment
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+")
// Allowing backspace
&& !(e.KeyChar == '\b')
// Allowing decimals
&& !((e.KeyChar == '.' && textBox1.Text.IndexOf('.') == -1))
/* The following is allowing negative signs ONLY if it is in the first space, otherwise it does not allow it!*/
&& (!((e.KeyChar == '-') && (textBox1.Text == "")))
//End if bracket (below)
)
// if e.Handled = true; it does not allow the keystroke to be added! (and it's not linking to a function or anything complex like that too!)
{
e.Handled = true;
}
}
Please help!