问题
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;
}
}
- frm.controls will give all controls
- 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