I've written the following to restrict a WPF textbox to only accept integers and also only accept a number less than or equal to 35:
In my WindowLoaded event I create a handler for 'OnPaste':
DataObject.AddPastingHandler(textBoxWorkflowCount, OnPaste);
OnPaste consists of the following:
private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
if (!IsNumeric(e.Source.ToString(), NumberStyles.Integer)) e.Handled = true;
}
and our function to force numerics only is as follows:
public bool IsNumeric(string val, NumberStyles numberStyle)
{
double result;
return double.TryParse(val, numberStyle, CultureInfo.CurrentCulture, out result);
}
The specific textbox that is having the error should also be limited to a number <=35. To do this I've added the following TextChanged event:
private void TextBoxWorkflowCountTextChanged(object sender, TextChangedEventArgs e)
{
try
{
if (textBoxWorkflowCount == null || textBoxWorkflowCount.Text == string.Empty || Convert.ToInt32(textBoxWorkflowCount.Text) <= 35) return;
MessageBox.Show("Number of workflow errors on one submission cannot be greater then 35.", "Workflow Count too high", MessageBoxButton.OK, MessageBoxImage.Warning);
textBoxWorkflowCount.Text = "";
}
catch(Exception)
{
// todo: Oh the horror! SPAGHETTI! Must fix. Temporarily here to stop 'pasting of varchar' bug
if (textBoxWorkflowCount != null) textBoxWorkflowCount.Text = "";
}
}
Although this does the job and works it's very nasty/hackish and I would love to know how it could be done better for sake of improving myself... Especially so without having to swallow an exception.