Reputation: 1186
I am trying to remove the last entered letter in a texbox. I am using a Regex to determine if the entry is valid. However, the code I have only checks the first character, and stops after that. Not sure what I am doing wrong.
I want the user to be able to input as many numbers as they want (including negative numbers).
Here is my code:
private void textBox_Gen_Offset_TextChanged(object sender, EventArgs e)
{
Regex pattern = new Regex("[-+]?[0-9]*");
if (pattern.IsMatch(textBox_Gen_Offset.Text))
{
UpdateTotal();
}
else
{
if (textBox_Gen_Offset.Text.Length > 0)
{
textBox_Gen_Offset.Text = textBox_Gen_Offset.Text.Substring(0, textBox_Gen_Offset.Text.Length - 1);
}
}
}
Upvotes: 0
Views: 96
Reputation: 2043
I'm not an expert on regex, but you could check if entered data is numeric by trying to parse is as an int or a double (for integers or floating point numbers respectively).
int intInTheBox;
if (int.TryParse(textBox_Gen_Offset.Text, out intInTheBox))
{
//Do stuff if it's an int
}
double doubleInTheBox;
if (double.TryParse(textBox_Gen_Offset.Text, out doubleInTheBox))
{
//Do stuff if it's a double
}
Upvotes: 1