Masked TextBox in WPF using VB.NET

In this article I am going to show how we can create a masked textbox in WPF.
  • 3681

While taking input from the user it's very necessary that user should type input in correct datatype, mean if integer value required then user should type integer value and if string required then should type string. In WPF I am going to show how we can bound user to do that, by masking textbox.

This is my XAML code:

<Window x:Class="Window1"
    Title="Window1" Height="300" Width="300">
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="98,80,0,0" Name="textBlock1"Text="Enter Value:" VerticalAlignment="Top" >

        <TextBox Height="23" HorizontalAlignment="Left" Margin="184,80,0,0" Name="textBoxValue"PreviewTextInput="textBoxValue_PreviewTextInput" DataObject.Pasting="textBoxValue_Pasting"VerticalAlignment="Top" Width="120">



Here I use 2 property of TextBox  PreviewTextInput="textBoxValue_PreviewTextInput"DataObject.Pasting="textBoxValue_Pasting". 

This is XAML.vb code:

Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Windows.Navigation
Imports System.Windows.Shapes
Class Window1
    Private Sub textBoxValue_PreviewTextInput(ByVal sender As ObjectByVal e AsTextCompositionEventArgs)
        e.Handled = Not TextBoxTextAllowed(e.Text)
    End Sub

    Private Sub textBoxValue_Pasting(ByVal sender As ObjectByVal e AsDataObjectPastingEventArgs)
        If e.DataObject.GetDataPresent(GetType([String])) Then
            Dim Text1 As [String] = DirectCast(e.DataObject.GetData(GetType([String])), [String])
            If Not TextBoxTextAllowed(Text1) Then
            End If
        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
End Class

When run the application then:


Image 1.

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


More Articles

© 2020 DotNetHeaven. All rights reserved.