10

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;
        }
     }
10
  • 1
    That's because when you set entry.Text OnAgeTextChanged is going to get called again. My suggestion would be to change your validation to entry.Unfocused when the user should be finished editing the text that or you could unsubscribe your entry to OnAgeTextChanged at the start of the method then after setting all the text resubscribe at the end of the method. Jun 15, 2018 at 15:21
  • @Nick how would I do the second one? I know in vb.NET I can use RemoveHandler, but how would it be done in c#?
    – David
    Jun 15, 2018 at 15:22
  • You're already doing it in the method move entry.TextChanged -= OnAgeTextChanged; to the beginning of your try and maybe add a finally after your catch and move entry.TextChanged += OnAgeTextChanged; there. Jun 15, 2018 at 15:26
  • @Nick Hmm, it still loops over multiple times after doing as you said
    – David
    Jun 15, 2018 at 15:37
  • 1
    honestly I'd take out the event unsubscribe and subscribe events ('entry.TextChanged += OnAgeTextChanged;'), they don't work the way you think they do, not in this instance anyway.
    – JoeTomks
    Jun 18, 2018 at 11:12

4 Answers 4

7

The way that I resolved this issue in the end was using a separate class to handle my validations.

My validation class:

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class viewModel : INotifyPropertyChanged
{
 public event PropertyChangedEventHandler PropertyChanged;

 private string age_;
 public string Age { get { return age_; } set { if (age_ != value) { age_ = ProcessAge(value); OnPropertyChanged(); } } }

 private string ProcessAge(string age)
 {
    if (string.IsNullOrEmpty(age))
        return age;

    if (age.Length > 3)
        age = age.Substring(0, 3);

    if (age.StartsWith("0"))
        age = age.Remove(0, 1);

    return age.Replace(".", "").Replace("-", "");
 }

 private void OnPropertyChanged([CallerMemberName] string propertyName = null)
 {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
 }
}

Then, I can bind the form to use this class, with:

public MainPage()
    {
        InitializeComponent();
        BindingContext = new viewModel();
    }

And finally, to bind the entry control to use the Age property, I set the Text property

Text="{Binding Age, Mode=TwoWay}"

What this now does, is every time the value in the Age control changes, it will look to the Age property in the new class and see that to set it, it needs to go through ProcessAge to validate it, and this is where the checks are now done.

This is faster, as it only occurs once per key press and there's no fiddling around required with subscribing and unsubscribing the TextChanged event and no loops.

5
+25

It looks like the object sender you've received from the event is not the exact same instance of Entry generated by your XAML.

So, that can explain the issue:

entry.TextChanged -= OnTextChanged; has no effect to your code at all, this object have no subscribers yet

Then, at the end of your stuff, you set:

entry.TextChanged += OnAgeTextChanged; now it does. You're 'immortalizing' this instance (sender).

I'm wondering if it's an elegant way to solve your specific problem (later I'll try to post some alternatives if it works) but to make it works, I guess you can try to unsubscribe and subscribe again over the txtAge object reference directly:

private void OnAgeTextChanged(object sender, TextChangedEventArgs e)
{
    try
    {
        txtAge.TextChanged -= OnAgeTextChanged;

        if (e.NewTextValue?.Length > 3 ?? false)
            txtAge.Text = e.OldTextValue;

        string strNumber = txtAge.Text;

        if (strNumber.Contains(".") || strNumber.Contains("-"))
        {
            strNumber = strNumber.Replace(".", "").Replace("-", "");
            txtAge.Text = strNumber;
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine("Exception caught: {0}", ex);
    }
    finally
    {
        txtAge.TextChanged += OnAgeTextChanged;
    }
 }

I hope it helps.

1

This should solve your problem:

private void OnAgeTextChanged(object sender, TextChangedEventArgs e)
{
   var entry = (Entry)sender;
   entry.TextChanged -= OnAgeTextChanged;
    try
    { //[...] Your stuff
    }

    catch(Exception ex)
    {
        //[...] Your other stuff
    }
    finally{
          entry.TextChanged += OnAgeTextChanged;
    }
}

Because in the code below, you change the text while the event handler is still listening, so it will be fired again at least 1 time.

if (strName.Contains(".") || strName.Contains("-"))
{
    strName = strName.Replace(".", "").Replace("-", "");
    entry.Text = strName;
}
0

It's best to use the entry unfocused event, this way it won't make so many calls to the event handler and hence the performance will be improved!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.