/// <summary>
/// 格式化输入文本框(只允许输入字母且每隔两个字符添加空格空位)
/// </summary>
public class FormatTextBox : RadTextBox
{
#region define、attribute
/// <summary>
/// 是否为退格键
/// </summary>
private bool IsEmptyKey = false;
/// <summary>
/// 枚举类型,False表示不转换,True表示转换为大写
/// </summary>
public enum ToUppers
{
False,
True,
}
private ToUppers to_Upper;
[DefaultValue(ToUppers.False)]
public ToUppers To_Upper
{
get
{
return to_Upper;
}
set
{
to_Upper = value;
}
}
#endregion
#region verride event
protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
base.OnKeyPress(e);
SetStandard(e);
}
/// <summary>
/// 只允许输入字母和退格键
/// </summary>
/// <param name="e">键盘按键</param>
private void SetStandard(System.Windows.Forms.KeyPressEventArgs e)
{
//只允许输入字母
Regex regex = new Regex("^[a-zA-Z\b]");
MatchCollection mc = regex.Matches(e.KeyChar.ToString());
foreach (Match ma in mc)
{
e.Handled = false;
if (e.KeyChar == ‘\b‘)
{
IsEmptyKey = true;
}
return;
}
e.Handled = true;
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
if (ToUppers.True.ToString() == To_Upper.ToString())
{
this.Text = this.Text.ToUpper();
this.Select(Text.Length, 0);
}
}
public override string Text
{
get
{
return base.Text;
}
set
{
//退格键
if (IsEmptyKey)
{
base.Text = value;
IsEmptyKey = false;
return;
}
if (value.Length < 2)
{
base.Text = value;
return;
}
StringBuilder sb = new StringBuilder();
string content = value.Trim();
content = content.Replace(" ", string.Empty);
try
{
int length = content.Length / 2;
int num = 2;
if (content.Length > 0)
{
for (int i = 0; i < length; i++)
{
num = 2 * i;
string tempStr = content.Substring(num, 2);
sb.Append(tempStr);
sb.Append(" ");
}
}
//长度为奇数时追加最后一个字符
int remainder = content.Length % 2;
if (remainder == 1)
{
string tempStr = content.Substring(content.Length - 1, 1);
sb.Append(tempStr);
}
}
catch
{
return;
}
base.Text = sb.ToString().ToUpper();
return;
}
}
#endregion
}