如何计算带有红色背景的标签 [英] How to count labels with red backcolor
本文介绍了如何计算带有红色背景的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨朋友们,
我的Winforms应用程序中有10个标签,c#,背面颜色为红色。
有没有人可以帮忙把它写成输出
红色标签的数量是:10。
谢谢!
我的尝试:
我尝试使用计数器,但没有结果。
Hi friends,
I have ten labels in my Winforms app in c#, they have back color "red".
Does any one can just help to write this as output
The number of red labels are: 10.
Thank You!
What I have tried:
I try with counter, but no result.
Label lb;
int count = 1; ;
if (lb.BackColor == Color.Red)
{
count++;
}
label6.Text = count.ToString();
推荐答案
这是怎么回事你可能想要这样做...
初始化整数计数器。
使用foreach循环(参考: foreach,in(C#Reference) [ ^ ])使用Controls集合逐步浏览表单上的所有控件表格(参考:如何:使用控件集合访问控件 [ ^ ])
使用control.GetType()测试每个控件的类型(参考: Object.GetType方法(系统) [ ^ ])并将其与typeof
标签进行比较(参考: typeof(C#Reference) [ ^ ])
如果匹配类型,那么你可以检查BackColor
是Color.Red
...提示,您可能需要施放
控件到显式标签,以便访问BackColor
属性(参考:转换和类型转换(C#编程指南) [ ^ ])
您可以使用MessageBox.Show()
来显示结果(参考: MessageBox.Show方法(System.Windows.Forms) [ ^ ])
This is how you probably want to do it...
Initialise a integer counter.
Use a foreach loop (Ref:foreach, in (C# Reference)[^]) to step through all of the controls on your form using the Controls collection of the form (Ref: How to: Access Controls by using the Controls Collection[^] )
Test the type of each control using control.GetType() (Ref: Object.GetType Method (System)[^] ) and compare it to thetypeof
Label (Ref:typeof (C# Reference)[^])
If they match types then you can check to see ifBackColor
isColor.Red
... Hint, you might have tocast
the control to an explicit Label in order to access theBackColor
property (Ref: Casting and Type Conversions (C# Programming Guide)[^] )
You can useMessageBox.Show()
to display the results (Ref: MessageBox.Show Method (System.Windows.Forms)[^] )
WinForm [ ^ ]继承自Control和Control包含 Controls [ ^ ];)
所以,你可以遍历控件集合。但是,我需要警告你!一些控件可以包含另一个控件...
WinForm[^] inherits from Control and Control contains a collection of Controls[^] ;)
So, you can iterate through the collection of controls. But, i need to warn you! Some of controls can contain another controls...
试试这个
try this
int count = 0;
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(Label))
if (((Label)c).BackColor == Color.Red)
count++;
}
注意:如果标签存在于任何容器控件中,那么您还必须迭代容器,如this [ ^ ]
这篇关于如何计算带有红色背景的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文