Hello, you can try this:
a = b + c ;
name_of_label_to_be_changed = "Label" + a.ToString();
this.Controls[name_of_label_to_be_changed].Forecolor = System.Drawing.Color.Red;
I hope it helps.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I am writing a Windows Form application with Visual Studio C# under .Net framework.
I have a number of Labels on the form, say, Label1, Label2, Label3, etc.
I need to programmatically read and change some properties of a Label, based on the Label's name. That is, as a result of a calculation, I might need to change, say, Label2's color.
{
a = b+c ;
name_of_label_to_be_changed = "Label" + a.ToString();
[[[something_or_somecode_that_uses_name_label_to_be_changed]]].Forecolor = System.Drawing.Color.Red
}
How can I do that? How can I access a Label based on its name?
In Delphi, where I came from, there is a FindComponent function that does this.
I see that VisualC# has a FindControl method but that seems to be for web pages and doesn't even seem to be available in my setup.
Thanks in advance for any advice.
Hello, you can try this:
a = b + c ;
name_of_label_to_be_changed = "Label" + a.ToString();
this.Controls[name_of_label_to_be_changed].Forecolor = System.Drawing.Color.Red;
I hope it helps.
Hi JeffreySchwartz-9279,
Regarding DarrenPeterson's code, I would like to point out that you need to change “()” to "[]".
this.Controls[name_of_label_to_be_changed].ForeColor = System.Drawing.Color.Red;
And you can also use ControlCollection.Find() method as DavidLowndes-6766 said.
this.Controls.Find(name_of_label_to_be_changed, true).FirstOrDefault().ForeColor = Color.Red;
Best Regards,
Daniel Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Try the following in a separate project to get instant gratification; put some controls in the form including a TextBox
. The Controls collection is all the controls whose parent is the form; this will not show controls whose parent is not the form. Note that c.GetType().Name
is the type, such as Button
, Label
or TextBox
.
StringBuilder sb = new StringBuilder(string.Empty);
foreach (Control c in Controls)
{
if (c.GetType().Name == "Label")
sb.Append(c.Name + " " + c.GetType().Name + "!!!\r\n");
else
sb.Append(c.Name + " " + c.GetType().Name + "\r\n");
}
textBox1.Text = sb.ToString();