Cancel Key press event

后端 未结 7 2079
别那么骄傲
别那么骄傲 2021-01-05 07:37

How can I return the key?, mean if I want to allow only integer values in the textbox, how can I don\'t allow user to not enter non-integers, regarding, KeyPress

7条回答
  •  旧巷少年郎
    2021-01-05 08:29

    You can inherit from TextBox and then:

    Protected Overrides Sub OnTextInput(ByVal e As System.Windows.Input.TextCompositionEventArgs)
    
            Dim newChar As Char = Convert.ToChar(e.Text)
            If Not [Char].IsDigit(newChar) Then e.Handled = True
    
    End Sub
    

    C# version

    protected override void OnTextInput(System.Windows.Input.TextCompositionEventArgs e)
    {    
        char newChar = Convert.ToChar(e.Text);        
        if (!Char.IsDigit(newChar)) e.Handled = true; 
    }
    

提交回复
热议问题