Masked TextBox WPF in VB.NET

Here we will see that how we can bound user to type input in the TextBox with the correct datatype, by masking textbox.
  • 3132
Download Files:
 

Here we will see that how we can bound user to type input in the TextBox with the correct datatype, by masking textbox.

Making TextBox as a Masking TextBox

When we take a input from the user it's very necessary that user should type input with correct datatype, that means if string value required then user should type string value otherwise does not allow to input in the TextBox and if integer required then should type integer.

XAML code

The below code restrict the user to input integer value.

<Window x:Class="MainWindow"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="MainWindow" Height="350" Width="525">

    <Grid>

        <TextBlock Height="23" HorizontalAlignment="Left" Margin="98,80,0,0" Name="textBlock1" Text="Enter Value:" VerticalAlignment="Top" >

       </TextBlock>

        <TextBox HorizontalAlignment="Left" Margin="184,80,0,200" Name="textBoxValue" PreviewTextInput="textBoxValue_PreviewTextInput"                         DataObject.Pasting="textBoxValue_Pasting" Width="200" Background="CornflowerBlue" Foreground="DarkRed">

   </TextBox>

    </Grid>

</Window>

 

Add the following code with the event of TextBox.

Private Sub textBoxValue_PreviewTextInput(ByVal sender As Object, ByVal e As TextCompositionEventArgs)
        e.Handled = Not TextBoxTextAllowed(e.Text)
    End Sub

    Private Sub textBoxValue_Pasting(ByVal sender As Object, ByVal e As DataObjectPastingEventArgs)
        If e.DataObject.GetDataPresent(GetType([String])) Then
            Dim Text1 As [String] = DirectCast(e.DataObject.GetData(GetType([String])), [String])
            If Not TextBoxTextAllowed(Text1) Then
                e.CancelCommand()
            End If
        Else
            e.CancelCommand()
        End If
    End Sub

Private Function TextBoxTextAllowed(ByVal Text2 As [String]) As [Boolean]
        Return Array.TrueForAll(Of [Char])(Text2.ToCharArray(), Function(c As [Char]) [Char].IsDigit(c) OrElse [Char].IsControl(c))
    End Function

 

Now run the application and test it.

 

t1.gif

 

Figure1.gif

 

If user try to type string value in this textbox then he can't type. Permission only to type integer value.


t2.gif

 

Figure2.gif

Categories

More Articles

© 2018 DotNetHeaven. All rights reserved.