C# - How to make a textbox that only accepts numbers or only characters
in this c# tutorial we will see how to make a textbox that only accepts numbers or only characters in C# .
Project Source Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class TextBox_Numbers_Characters : Form
{
public TextBox_Numbers_Characters()
{
InitializeComponent();
}
private void TXTB_ONLY_CHAR_KeyPress(object sender, KeyPressEventArgs e)
{
if(!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar))
{
e.Handled = true;
}
}
private void TXTB_ONLY_NUMBER_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
private void TXTB_CHAR_AND_NUMBER_KeyPress(object sender, KeyPressEventArgs e)
{
// allow digit + char + white space
if (!char.IsControl(e.KeyChar) && !char.IsLetterOrDigit(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar))
{
e.Handled = true;
}
}
}
}
=> OutPut :
Download Projects Source Code