TechSapphire Monday, 2024-06-17, 10:30 PM
Site menu
Login form
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:


    <Window x:Class="TestApplication.MainWindow"
            Title="MainWindow" Height="350" Width="525">
            <TextBox Width="400" Height="50" PreviewTextInput="TextBox_PreviewTextInput"    />




    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() {
     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);


    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]
    SSRS [1]
    Sql Server Reporting Services
    Copyright MyCorp © 2024