TechSapphire Wednesday, 2018-02-21, 12:11 PM
Site menu
Login form
News
Play Games
  • Deep Freeze
  • Ice Slide
  • Gyroball
  • Fat Fish
  • Bush Royal Rampage
  • Keypress event in WPF to validate integer input is replaced by PreviewTextInput in C#

    In WPF we don't have keypress event, generally people used keypress event in windows forms application to validate text input. Now in this example I have showed how you can validate input from textbox using PreviewTextInput event. In this example I validated input to accept float values, you can use this to validate integer or any other number type validation.

    Code used in example is:

    XAML:

    <Window x:Class="TestApplication.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>
            <TextBox Width="400" Height="50" PreviewTextInput="TextBox_PreviewTextInput"    />
        </Grid>
    </Window>

     

     

    C#:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    namespace TestApplication {
     /// <summary>
     /// Interaction logic for MainWindow.xaml
     /// </summary>
     public partial class MainWindow: Window {
     public MainWindow() {
     InitializeComponent();
     }
    
     private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) {
     if (e.Text != "." && IsNumber(e.Text) == false) {
     e.Handled = true;
     } else if (e.Text == ".") {
     if (((TextBox) sender).Text.IndexOf(e.Text) > -1) {
     e.Handled = true;
     }
     }
     }
     private bool IsNumber(string Text) {
     int output;
     return int.TryParse(Text, out output);
     }
     }
    }

     

    Categories
    Programming [27]
    Tips for programming
    Security [2]
    Security Tips
    Google [1]
    Use google faster then ever you use
    Project [14]
    HTML [2]
    Electronics [0]
    Data Structure [0]
    Database [16]
    SQL SERVER
    SSRS [1]
    Sql Server Reporting Services
    Copyright MyCorp © 2018