源於"博問"上的一篇文章,很多時候我們的控制項需要限定字元輸入的MaxLength,但是遇到中英文混合的情況,對於長度的判定就有點複雜,現提供TextBoxBase繼承控制項的通用方法:
Code
public static void OnTextBoxValueChanged(object sender, EventArgs e)
{
TextBoxBase txtbox = sender as TextBoxBase;
if (txtbox != null)
{
txtbox.TextChanged -= OnTextBoxValueChanged;
if (Encoding.Default.GetByteCount(txtbox.Text) >
txtbox.MaxLength && txtbox.Text.Length > 0)
{
string tmp = txtbox.Text.Substring(0,txtbox.Text.Length - 1);
while (Encoding.Default.GetByteCount(tmp) >txtbox.MaxLength && tmp.Length > 0)
{
tmp =tmp.Substring(0, tmp.Length - 1);
}
int start = txtbox.SelectionStart;
int length = txtbox.SelectionLength;
txtbox.Text = tmp;
txtbox.SelectionStart = start;
txtbox.SelectionLength = length;
}
txtbox.TextChanged += OnTextBoxValueChanged;
}
}
轉載請註明原文地址:http://www.cnblogs.com/winzheng/archive/2009/03/04/1402721.html
- 在需要驗證長度的控制項的ValueChanged 事件上響應此方法即可.