I have been working on Custom TextBox control, which only allows alphanumeric characters. Note that I have not restricted characters from KeyPress, KeyUp event as I don't want to restrict copy/paste or any other operation that should be allowed generally. I have only trimmed non-alphanumeric character on paste operation. However, I am not sure whether the code I wrote is good or bad as I have very little experience of desktop application.
using System;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace SaintThomas.UserControls
{
class TextBoxForUserName : TextBox
{
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
this.SuspendLayout();
int startPos = this.SelectionStart;
if (Regex.IsMatch(this.Text, "[^0-9_A-Z]", RegexOptions.IgnoreCase))
{
int reduceStartPos = this.Text.Length;
this.Text = Regex.Replace(this.Text, "[^0-9_A-Z]", "", RegexOptions.IgnoreCase);
startPos = (startPos <= 0) ? 0 : startPos - (reduceStartPos - this.Text.Length);
if (this.Text.Length < startPos)
{
startPos = this.Text.Length;
}
this.SelectionStart = startPos;
}
this.ResumeLayout();
}
}
}