473,320 Members | 2,145 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Alphanumeric character validation in C#

Hey all,

I have to validate a textbox in windows forms for alphanumeric
characters such that non alphanumeric key presses are ignored.

Some help would be appreciated

May 30 '07 #1
7 21347
On May 30, 8:15 pm, kanepa...@hotmail.com wrote:
Hey all,

I have to validate a textbox in windows forms for alphanumeric
characters such that non alphanumeric key presses are ignored.

Some help would be appreciated
try isDigit and isChar functions when validating the .keydown action.

May 30 '07 #2

kanepa...@hotmail.com wrote:
Hey all,

I have to validate a textbox in windows forms for alphanumeric
characters such that non alphanumeric key presses are ignored.

Some help would be appreciated

This is not complete but something like this I gues:

You can add KeyDown event handler to your textbox ... for example:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.OemMinus) // and of course more checks
here ....
{
e.SuppressKeyPress = true;
e.Handled = true;
}
}

May 30 '07 #3
//
// AlphaNumTextBox.cs
//

using System;
using System.Windows.Forms;

namespace AlphaNumericTextBox
{
/// <remarks>
/// A text box to contain alphanumeric data
/// </remarks>
internal sealed class AlphaNumTextBox : TextBox
{
#region Fields

private bool isBack = false;
private bool isAlphaNum = false;

#endregion

#region Event raisers

protected override void OnKeyDown(KeyEventArgs e)
{
Keys k = e.KeyCode;

if (k == Keys.Back)
{
this.isBack = true;
this.isAlphaNum = false;
}
else
{
bool isAlpha = !e.Alt && !e.Control && (k >= Keys.A && k <=
Keys.Z);

// Determine whether the keystroke is a number
bool d0d9 = k >= Keys.D0 && k <= Keys.D9;
bool numpad = k >= Keys.NumPad0 && k <= Keys.NumPad9;
bool isNumber = (!e.Alt && !e.Control && !e.Shift) && (d0d9
|| numpad);

this.isBack = false;
this.isAlphaNum = isAlpha || isNumber;
}
base.OnKeyDown(e);
}

protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!this.isBack && !this.isAlphaNum)
{
e.Handled = true;
return;
}

char c = e.KeyChar;

if (this.isBack && this.SelectionStart 0)
{
int currentPosition = SelectionStart;
this.Text = this.Text.Substring(0, this.TextLength - 1);
this.SelectionStart = currentPosition - 1;
e.Handled = true;
return;
}

if (this.isAlphaNum && this.SelectionStart < this.MaxLength)
{
int currentPosition = SelectionStart;
this.Text = this.Text.Insert(currentPosition,
Char.ToUpper(c).ToString());
this.SelectionStart = currentPosition + 1;
e.Handled = true;
return;
}

base.OnKeyPress(e);
}

#endregion
}
}
Bye,
Luigi.
May 30 '07 #4
On May 30, 1:31 pm, Daniel Cigic <daniel.ci...@googlemail.comwrote:
kanepa...@hotmail.com wrote:
Hey all,
I have to validate a textbox in windows forms for alphanumeric
characters such that non alphanumeric key presses are ignored.
Some help would be appreciated
I tried both the above . e does not have a property called KeyCode
This is not complete but something like this I gues:

You can add KeyDown event handler to your textbox ... for example:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.OemMinus) // and of course more checks
here ....
{
e.SuppressKeyPress = true;
e.Handled = true;
}
}

May 30 '07 #5
On Wed, 30 May 2007 19:31:01 +0200, Mahmoud Al-Qudsi <mq****@gmail.comwrote:
On May 30, 8:15 pm, kanepa...@hotmail.com wrote:
>Hey all,

I have to validate a textbox in windows forms for alphanumeric
characters such that non alphanumeric key presses are ignored.

Some help would be appreciated

try isDigit and isChar functions when validating the .keydown action.

Even better,

Char.IsLetterOrDigit(char), you need to use the KeyPress event to get the characters and cancel (Handled) the event.

--
Happy coding!
Morten Wennevik [C# MVP]
May 30 '07 #6
On Wed, 30 May 2007 10:51:07 -0700, <ka*******@hotmail.comwrote:
I tried both the above . e does not have a property called KeyCode
Sure it does, if you are actually handling the KeyDown event which has the
KeyEventArgs parameter:

http://msdn2.microsoft.com/en-us/lib...s.keycode.aspx

That said, it seems to me that Morton's advice about using the KeyPress
event instead is better. Set the e.Handled property to "true" to avoid
non-alphanumeric characters from being entered.

Also note that there's a MaskedTextBox that will do this sort of filtering
for you. If all you are trying to do is restrict input to alphanumerics,
that might be a better choice.

Pete
May 30 '07 #7
Hey all,
>
I have to validate a textbox in windows forms for alphanumeric
characters such that non alphanumeric key presses are ignored.
Filtering at key-press is usually the bad approach.
It will mess-up a languages that have more complex input
(dead-keys, IME, etc.)
--
Mihai Nita [Microsoft MVP, Windows - SDK]
http://www.mihai-nita.net
------------------------------------------
Replace _year_ with _ to get the real email
May 31 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Shozi | last post by:
Dear All, My project is basically about the personal record keeping of user's data. Now user can customize their data entry form by adding/removing the desired fields for personal information...
3
by: Bill | last post by:
I just ran into a situation where string data from a mainframe contained a couple of non-alphanumeric characters (hex CC and C8). I was parsing a field that occurred after these unexpected...
2
by: VB Programmer | last post by:
I have several required field validators on each step of my CreateUserWizard. When I click Next it goes to the next step, even though the user hasn't typed anything in. I placed each "page"...
2
by: joe.minga | last post by:
This is an assignment for an VB intro class and I have no experience. Any help would be appreciated. I need to accept users name as input and then check for the existence of a specific letter in...
1
by: sonald | last post by:
Dear All, I am working on a module that validates the provided CSV data in a text format, which must be in a predefined format. We check for the : 1. Number of fields provided in the text file,...
6
by: Napalm | last post by:
Hi All, i'm new to posting in this forum , yet i have been lurking for a while. I was wondering if anyone has advice on how i can add a validation of a textbox . I'd like to set a min of 2...
3
by: pradeep | last post by:
Hi How i check alphnumeric & space validation for input text ? e.g. input : "abc GNM 2" is valid & input : "abc GNM %2" is invalid guide me.
11
kaleeswaran
by: kaleeswaran | last post by:
now i am creating login page... so in my name field i should get a charcter value only other wise it should be shows the error ... how to do the validation ?.... send me the code plzzzzzzzzz
5
by: hamsterchaos | last post by:
<asp:RegularExpressionValidator id="valRegEx" runat="server" ControlToValidate="textbox1" ValidationExpression=" " ErrorMessage="* Please only enter alphanumeric values and make sure...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.