如何遍历所有 textBox 控件并更改关联的标签颜色 [英] How to loop through all textBox controls and change associated label color
本文介绍了如何遍历所有 textBox 控件并更改关联的标签颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
foreach (Control c in this.Controls)
{
if (c is TextBox && c.Text.Length==0)
{
// [Associatedlabel].ForeColor = System.Drawing.Color.Red;
err = true;
}
而不是[Associatedlabel],我想将每个文本框与标签相关联,所以最终文本框附近的所有标签都是空的,都是红色的,怎么做?谢谢.
instead of [Associatedlabel], I want to associate each textbox to label, so eventually all labels near the textbox that are empty will be red, how it can be done? Thanks.
推荐答案
您可以先手动将 TextBox
的 Tag 属性设置为这些标签.标签旨在包含用户定义的数据,因此您可以在其中放置任何 object
.然后你可以简单地做:
You can first manually set your TextBox
's Tag property to these labels. Tag is meant to contain user-defined data, so you can place any object
there. Then you can do simply:
foreach (Control c in this.Controls)
{
if (c is TextBox && c.Text.Length==0 && c.Tag is Label)
{
((Label)c.Tag).ForeColor = System.Drawing.Color.Red;
err = true;
}
}
这是最简单的解决方案,但还有一些更复杂的解决方案.
This is the simplest solution, but a few more sophisticated exists though.
- 创建一个包含标签、文本框和自定义行为的自定义复合控件;
- 创建一个源自文本框的控件,该控件存储有关与其连接的标签的信息(如 Hans Passant 建议的那样)
- 创建一个
Dictionary
或Dictionary
,允许在运行时解决此类问题(Steve 的想法有所不同).
- Creating a custom composite control consisting of a label, textbox and custom behavior;
- Creating a control deriving from a textbox, which stores information about label it is connected with (as Hans Passant suggests)
- Creating a
Dictionary<TextBox, Label>
orDictionary<Control, Label>
, which allows resolving such matters in runtime (variation on Steve's idea).
这篇关于如何遍历所有 textBox 控件并更改关联的标签颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文