Error in leave even customization

I have created an event that checks to make sure that a field only contains numbers when leaving the field. I got that to work, but now the issue is when I click in the field then click out without typing anything, I get an error. My code is below. followed by the error.

private void txtSSNum_Leave(object sender, System.EventArgs args)
	{
        // ** Place Event Handling Code Here **
        var ssnum = txtSSNum.Value.ToString();
        //(TEST) MessageBox.Show(ssnum);
        try
        {
            int num = Convert.ToInt32(ssnum);
        }
        catch (Exception)
        {
            MessageBox.Show("Shipset Number Cannot Contain Letters.");
            txtSSNum.Value = " ";
        }
	}

Application Error

Exception caught in: App.SalesOrderEntry.SalesOrderForm.EP.Customization.OrdEntryCustomization.CustomCode.0

Error Detail

Message: Object reference not set to an instance of an object.
Program: App.SalesOrderEntry.SalesOrderForm.EP.Customization.OrdEntryCustomization.CustomCode.0.dll
Method: txtSSNum_Leave

Client Stack Trace

at Script.txtSSNum_Leave(Object sender, EventArgs args)
at System.Windows.Forms.Control.OnLeave(EventArgs e)
at Infragistics.Win.UltraWinEditors.TextEditorControlBase.OnLeave(EventArgs e)
at System.Windows.Forms.Control.NotifyLeave()
at System.Windows.Forms.ContainerControl.UpdateFocusedControl()

Does the Code validate? Try Actions > Test Code (F5).
I suspect that the object txtSSNum does not exist.

Either txtSSNum doesn’t exist or txtSSNum.Value is null instead of String.Empty like you’re expecting. Try placing the var ssnum assignment inside the try block.

It complies successfully and the txtSSnum is a UD field. Moving the declaration of the variable inside the try statement seems to work, thank you.

If it’s a UD field, you should use the dataView and not the controls.

correct the code as below and check.

var ssnum = Convert.ToString(txtSSNum.Value);