softshipper
softshipper

Reputation: 34119

Why is this event handler throwing an exception multiple times?

I have a XamMaskedInput for IP address input. It looks like: enter image description here

And the code behind:

using System;
using System.Diagnostics;
using System.Windows.Controls;
using System.Windows.Input;
using Infragistics.Controls.Editors;
using System.Net;

namespace Customizing.Views
{
    /// <summary>
    ///     Interaction logic for IpRangeFields.xaml
    /// </summary>
    public partial class IpRangeFields : UserControl
    {
        public IpRangeFields()
        {
            InitializeComponent();
        }

        private void Start_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            var input = (XamMaskedInput) sender;
            try
            {
                var ip = input.Text.Replace("-", ".");
                var address = IPAddress.Parse(ip);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Dispatcher.BeginInvoke((Action)(() => input.Focus()));
                e.Handled = true;
            }

        }
    }
}

When the user put wrong IP address, then it will throw System.FormatException. The problem is, it throws the exception for many times, that my wpf application frizzed. How can I solve this problem?

After exception occurs, it should not leave the input box. How can I do this?

Upvotes: 1

Views: 102

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149656

You're registering to an event that happens often, and you're using IPAddress.Parse which will throw if it can't parse the IP address.

Instead, check the validity of the IP address by using TryParse:

var ip = input.Text.Replace("-", ".");
IPAddress ipAddress;
if (!IPAddress.TryParse(ip, out ipAddress))
{
    // The address is invalid.
}

Another suggestion would be to use WPFs built in validation mechanisms to validate your IP. See this for more on how to do that.

Upvotes: 4

Related Questions