110,568
社区成员
发帖
与我相关
我的任务
分享
void 注册监听(TextBox txt1, TextBox txt2)
{
txt1.TextChanged += (s, e) =>
{
if (txt1.Text == txt2.Text)
txt1.ForeColor = System.Drawing.Color.Red;
else
txt1.ForeColor = System.Drawing.Color.Black;
};
}
这样就能少写代码。
“学过之后”你千万不要再说什么“写在一起”。这就好像是堆石头跟建筑设计的区别,是有着本质的区别的。 var tb = sender as TextBox;
if (tb != null)
{
var compare = this.Controls.Find("z" + Regex.Replace(tb.Name, @"\D", string.Empty), true);
if (compare != null && compare.Length > 0 && compare[0] is TextBox)
{
if (tb.Text == ((TextBox)compare[0]).Text)
{
tb.ForeColor = Color.Red;
}
}
}
你的id命名规则必须如你代码所写的那样一一对应
TextBox textbox1, textbox2;
TextBox tb1, tb2;
Dictionary<TextBox, TextBox> TextBoxMap { get; set; }
private void Initialize()
{
TextBoxMap = new Dictionary<TextBox, TextBox>()
{
{textbox1,tb1 },{textbox2,tb2}
};
TextBoxMap.Keys.ToList().ForEach(tb => tb.TextChanged += (s, e) =>
{
if (s is TextBox t1 && TextBoxMap.TryGetValue(t1, out TextBox t2))
{
t1.ForeColor = t1.Text == t2.Text ? Color.Red : Color.Black;
}
});
}