2
What I need:
A mask that works in the event keypress
of a TextBox
replacing what is not numerical and excessive hyphens with ""
.
What is my difficulty:
Check the entry of only one hyphen in the same expression.
I arrived at the solution using substring and only worked on KeyUP
, but wanted to arrive through an expression.
What I’ve already tried:
using System.Text.RegularExpressions;
private static Regex digitsOnly = new Regex(@"(:?[^\d\-])");
private void inputSequencial_KeyUp(object sender, KeyEventArgs e)
{
if (!String.IsNullOrEmpty(inputSequencial.Text)
{
inputSequencial.Text = digitsOnly.Replace(inputSequencial.Text, "");
//MatchCollection matches = Regex.Matches(inputSequencial.Text, "[\\-]");
//
//if (matches.Count > 1)
//{
// for (int i = 1; i <= matches.Count - 1; i++)
// {
// inputSequencial.Text = inputSequencial.Text.Substring(0, matches[i].Index-1) + inputSequencial.Text.Substring(matches[i].Index, inputSequencial.Text.Length);
// inputSequencial.Text = inputSequencial.Text.Replace(inputSequencial.Text[matches[i].Index].ToString(), "");
// }
//}
}
}
Expected result:
If you know a better way to do that, please point me out. Thank you for your attention.
could use a
masktextbox
?– Rovann Linhalis
I believe so, I am migrating from another language to C#/Winforms so I do not know much, I will search how it works masktextbox.
– Caique Romero
this. Just correcting:
MaskedTextBox
, then you can wear the mask:"0-000"
– Rovann Linhalis