'C# WPF - Dynamic textbox with handler checking numbers only

I have tried to combine dynamic textbox creation with checking that the user only types numbers but it keeps failing. I have a stack panel splMain where the textboxes are added into at runtime.

public void btnAddMore_Click(object sender, RoutedEventArgs e)
{
    TextBox x = new TextBox();
    x.Name = "new_textbox";
    x.AcceptsReturn = true;
    x.AddHandler(TextBox.PreviewKeyDownEvent, new KeyEventHandler(PreviewkeyDown));
    splMain.Children.Add(x);
}

private void PreviewkeyDown(object sender, KeyEventArgs e)
{
    Regex regex = new Regex("[^0-9]+");
    e.Handled = regex.IsMatch(e.);
}

Another Idea:

public void btnAddMore_Click(object sender, RoutedEventArgs e)
{
    TextBox tb = new TextBox();
    tb.KeyDown += new KeyEventHandler(NumericOnly);
    splMain.Children.Add(tb);
}

private void NumericOnly(System.Object sender, System.Windows.Input.TextCompositionEventArgs e)
{
    e.Handled = IsTextNumeric(e.Text);
}

private static bool IsTextNumeric(string str)
{
    System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]");
    return reg.IsMatch(str);
}

Its for WPF, actually to only allow insert Decimals or Double. Any one done this before or any brilliant ideas out there ?



Solution 1:[1]

I did this instead, Allows user to add dynamic text boxes that checks that the user only inputs numbers.

    public void btnAddMore_Click(object sender, RoutedEventArgs e)
    {
        TextBox x = new TextBox();
        x.Name = "new_textbox"; //Natural Number and pos int
        x.AcceptsReturn = true;
        x.AddHandler(TextBox.PreviewTextInputEvent, new TextCompositionEventHandler(PreviewkeyDown));
        splMain.Children.Add(x);
    }

    private void PreviewkeyDown(object sender, TextCompositionEventArgs e)
    {
        Regex regex = new Regex("[^0-9]+");
       e.Handled = regex.IsMatch(e.Text);
        if (regex.IsMatch(e.Text) == false)
        {
           return;
        }
        else
        {
            MessageBox.Show("Numbers Only Please");
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oxley Pilot