I'm trying to get a textbox keydown event to trap the backspace key down event. I have that working by adding a Class that overrides the textbox. What i don't know how to do is have that communicate with the class where the textbox is in the user control.
When a user types in the text box... say abcd or backspace, i need to update something on the usercontrol. let's just say i want to have something that displays how many characters are in the textbox. can someone help me with that. Here is what i have so far
Option Strict On
Imports System.Text.RegularExpressions
Partial Public Class Page
Inherits UserControl
Public Sub New()
InitializeComponent()
Dim textbox As New MyTextBox() With {.Width = 300, .Height = 100}
LayoutRoot.Children.Add(textbox)
End Sub
End Class
Public Class MyTextBox
Inherits TextBox
Protected Overrides Sub OnKeyDown(ByVal e As KeyEventArgs)
MyBase.OnKeyDown(e)
If e.Key = Key.Back Then
e.Handled = True
MyBase.OnKeyDown(e)
ElseIf e.Key = Key.Delete Then
e.Handled = True
MyBase.OnKeyDown(e)
End If
End Sub
End Class
thanks shannon
You shouldn't need to subclass TextBox to do this. Instead, add handler for the TextBox.TextChanged event right in your UserControl class. When this is called, the sender of the event should be your TextBox. You can then get the text from it and do what you need to do.
Update: Based on the comment, the following should work:
Partial Public Class Page
Inherits UserControl
Private TextBox1 as TextBox
Public Sub New()
InitializeComponent()
TextBox1 = New TextBox() With {.Width = 300, .Height = 100}
LayoutRoot.Children.Add(textbox)
End Sub
Private Sub OnTextChanged(sender as Object, e as TextChangedEventArgs) Handles TextBox1.TextChanged
If e.Key = Key.Back Then
e.Handled = True
ElseIf e.Key = Key.Delete Then
e.Handled = True
End If
End Sub
End Class
(My VB is a bit rusty, so the event handler syntax might not be completely correct.)
The basic idea is to get notified when text changes in the TextBox within your UserControl. This way you can modify the other parts of the UserControl as necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With