Note that there are some explanatory texts on larger screens.

plurals
  1. PORestricting a WPF Textbox to integers by swallowing an exception
    text
    copied!<p>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:</p> <p>In my WindowLoaded event I create a handler for 'OnPaste':</p> <pre><code>DataObject.AddPastingHandler(textBoxWorkflowCount, OnPaste); </code></pre> <p>OnPaste consists of the following:</p> <pre><code>private void OnPaste(object sender, DataObjectPastingEventArgs e) { if (!IsNumeric(e.Source.ToString(), NumberStyles.Integer)) e.Handled = true; } </code></pre> <p>and our function to force numerics only is as follows:</p> <pre><code>public bool IsNumeric(string val, NumberStyles numberStyle) { double result; return double.TryParse(val, numberStyle, CultureInfo.CurrentCulture, out result); } </code></pre> <p>The specific textbox that is having the error should also be limited to a number &lt;=35. To do this I've added the following TextChanged event: </p> <pre><code>private void TextBoxWorkflowCountTextChanged(object sender, TextChangedEventArgs e) { try { if (textBoxWorkflowCount == null || textBoxWorkflowCount.Text == string.Empty || Convert.ToInt32(textBoxWorkflowCount.Text) &lt;= 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 = ""; } } </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload