简体   繁体   中英

How to change label color of a usercontrol from another usercontrol ? C# .NET Framework

i have this project with 3 usercontrols and 1 form, the usercontrols appear on the form when a button is pressed. Now i need to change a label color on let's say "UserControl3" by clicking a button located in "UserControl1", i tried the following code but it didnt work

var name = new UserControl3();
name.label.ForeColor = Color.Green;

i also tried another way but it threw an exception, image below https://imgur.com/kBHUBoX

i then found another way that almost works as intended, by removing and adding the usercontrol. The problem is that then it goes on the main form that is supposed to be empty

var name = new UserControl3();
this.Controls.Remove(name);
this.Controls.Add(name);
name.label1.ForeColor = Color.Green;

the code above almost works as i want but i dont think its a good solution and im pretty sure there are other easier ways to make this work... Any kind of help is appreciated. Thanks

You do not have to re-create an instance of usercontrol but use the first instance created and just change the color of the control.

just this code:

name.label.ForeColor = Color.Green;

Define this code globally

var name = new UserControl3();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM