Set all Labels Font before opening the Form

为君一笑 提交于 2019-12-10 18:24:51

问题


Before opening the form I used following code to check if its label then change the font

foreach (Label ctl in frm.Controls)
{
    ctl.Font = usefontgrid;
}

But on first line return error because it check other control types such as textbox or button,etc.

How can I check if the object is only label then go to for each?


回答1:


Try this;

foreach (Control c in this.Controls)
{
    if (c is Label)
        c.Font = usefontgrid;
}

Or

foreach (var c in this.Controls.OfType<Label>())
{
    c.Font = usefontgrid;
}



回答2:


Its not clear where you place this code (should be after initialize component) but try

foreach (Label ctl in frm.Controls.OfType<Label>())
{
    ctl.Font = usefontgrid;
}

There is also the following Linq to do the same thing

foreach (Label ctl in frm.Controls.Where(x => x is Label))



回答3:


try this.

 foreach (Control ctl in frm.Controls)
    {
    if(ctl.GetType()==typeof(Label)){
        ctl.Font = usefontgrid;
    }
    }
  1. frm.controls will give all controls
  2. You need to check whether the control is a type of Label.


来源:https://stackoverflow.com/questions/18481029/set-all-labels-font-before-opening-the-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!