How to Create a Program that accepts Letters and Numbers using Textbox in Csharp

In this tutorial, we will learn how to create a program that only accepts letters and numbers using textbox using C# Windows Form Application. The main goal of the program is to filter out the symbols and special characters and you could use this in any part of your program to incorporate in your existing system.

Create a new project, , then Add 2 Textbox and 2 Label. For the Label1 Text Property, change it to “TYPE A LETTER - Accepts only Letter” for the Label2 Text Property, change it to “TYPE A NUMBER - Accepts only Number”


Finish product will be like this:


Go to Code Editor and type the code below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AcceptsNumberandAlpha
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((!char.IsLetter(e.KeyChar)) && (!char.IsWhiteSpace(e.KeyChar)) && (!char.IsControl(e.KeyChar)))
            {
                e.Handled = true;
            }
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((!char.IsNumber(e.KeyChar)) && (!char.IsControl(e.KeyChar)))
            {
                e.Handled = true;
            }
        }
    }
}

The final output:

In the first textbox you can only type a letter but not a number, similarly to the second textbox you can only type a number but not a letter.


How to Create a Program that accepts Letters and Numbers using Textbox in Csharp How to Create a Program that accepts Letters and Numbers using Textbox in Csharp Reviewed by code-dev on 10:00 PM Rating: 5

No comments:

Powered by Blogger.