在打开表单之前,我使用以下代码检查其标签是否更改了字体
foreach (Label ctl in frm.Controls)
{
ctl.Font = usefontgrid;
}
但是在第一行返回错误,因为它检查其他控件类型,如文本框或按钮等
如何检查对象是否只是标签然后转到每个?
答案 0 :(得分:4)
试试这个;
foreach (Control c in this.Controls)
{
if (c is Label)
c.Font = usefontgrid;
}
或者
foreach (var c in this.Controls.OfType<Label>())
{
c.Font = usefontgrid;
}
答案 1 :(得分:3)
不清楚你放置这段代码的位置(应该在初始化组件之后)但是尝试
foreach (Label ctl in frm.Controls.OfType<Label>())
{
ctl.Font = usefontgrid;
}
还有以下Linq做同样的事情
foreach (Label ctl in frm.Controls.Where(x => x is Label))
答案 2 :(得分:0)
试试这个。
foreach (Control ctl in frm.Controls)
{
if(ctl.GetType()==typeof(Label)){
ctl.Font = usefontgrid;
}
}