有个MaxLength属性的话恐怕不能达到要求,只能是手动处理了。
20个英文的话,长度是20(也可中英混杂),代码如下:
private void Form1_Load(object sender, EventArgs e)
{
SetTextBoxMaxLength();
}
void SetTextBoxMaxLength()
{
var cons = GetAllControls(this, typeof(TextBox));
cons.ForEach(con => {
con.TextChanged += new EventHandler(con_TextChanged);
});
}
void con_TextChanged(object sender, EventArgs e)
{
var txt = sender as TextBox;
int curLength = Encoding.Default.GetByteCount(txt.Text);
if (curLength > 6)
txt.BackColor = Color.Red;
else
txt.BackColor = Color.FromName("Window");
}
public static List<Control> GetAllControls(Control control, Type type)
{
List<Control> cons = new List<Control>();
foreach (Control c in control.Controls)
{
FindAllControls(c, ref cons, type);
if (c.GetType() == type) cons.Add(c);
}
return cons;
}
public static void FindAllControls(Control curCon, ref List<Control> cons, Type type)
{
foreach (Control c in curCon.Controls)
{
FindAllControls(c, ref cons, type);
if (c.GetType() == type) cons.Add(c);
}
}
具体的看需要修改关键代码就行了。