On my form I have 3 entry
controls. I'm trying to validate the 'Age' control, with the following validation rules:
Cannot enter more than 3 digits
Cannot enter a decimal place (.)
Cannot enter a hyphen (-)
To do this, I've set the 'TextChanged' property of my control to be
TextChanged="OnAgeTextChanged"
My OnAgeTextChanged
method is:
private void OnAgeTextChanged(object sender, TextChangedEventArgs e)
{
var entry = (Entry)sender;
try
{
if (entry.Text.Length > 3)
{
string entryText = entry.Text;
entry.TextChanged -= OnAgeTextChanged;
entry.Text = e.OldTextValue;
entry.TextChanged += OnAgeTextChanged;
}
string strName = entry.Text;
if (strName.Contains(".") || strName.Contains("-"))
{
strName = strName.Replace(".", "").Replace("-", "");
entry.Text = strName;
}
}
catch(Exception ex)
{
Console.WriteLine("Exception caught: {0}", ex);
}
}
However, when the if conditions are met, the event is being looped over multiple times, causing the application to run slowly.
For example, if I enter my age as 1234, it loops over the code multiple times so there's a delay, with the delay increasing each time the text gets changed.
What other way can I achieve this validation, but without the event being called multiple times?
EDIT
After updating the code to remove the TextChanged
trigger on my control before re-assigning it at the end of the method, it still loops over multiple times, and the number of loops increases with each key press.
Entry control xaml
<Entry x:Name="txtAge"
Placeholder="Age"
Keyboard="Numeric"
TextColor="DarkBlue"
PlaceholderColor="DarkBlue"
Completed="AgeCompleted"
HorizontalOptions="Start"
WidthRequest="55"
TextChanged="OnAgeTextChanged"
/>
TextChanged
event
private void OnAgeTextChanged(object sender, TextChangedEventArgs e)
{
var entry = (Entry)sender;
try
{
entry.TextChanged -= OnAgeTextChanged;
if (entry.Text.Length > 3)
{
entry.Text = e.OldTextValue;
}
string strName = entry.Text;
if (strName.Contains(".") || strName.Contains("-"))
{
strName = strName.Replace(".", "").Replace("-", "");
entry.Text = strName;
}
}
catch(Exception ex)
{
Console.WriteLine("Exception caught: {0}", ex);
}
finally
{
entry.TextChanged += OnAgeTextChanged;
}
}
entry.Text
OnAgeTextChanged
is going to get called again. My suggestion would be to change your validation toentry.Unfocused
when the user should be finished editing the text that or you could unsubscribe your entry toOnAgeTextChanged
at the start of the method then after setting all the text resubscribe at the end of the method.RemoveHandler
, but how would it be done in c#?entry.TextChanged -= OnAgeTextChanged;
to the beginning of your try and maybe add a finally after your catch and moveentry.TextChanged += OnAgeTextChanged;
there.