Reputation: 3
I am making a form system where i need to find a panel to change it's background using string imploration. I have done something similar for a label using the code below where numberEntered is a seperate interger in the program.
Label label = Controls.Find($"Num{numberEntered}", true).OfType<Label>().FirstOrDefault();
label.Text = "Text"
How can I do something similar for a panel where where I can find a panel using a seperate variable in the name? Such as $"Panel{number}"
I have already tried this:
Panel panel = Controls.Find($"Ans{answerNum}Panel", true).OfType<Panel>().FirstOrDefault();
panel.BackgroundImage = Programming_Project.Properties.Resources.MutliChoiceCorrectSelected;
However it throws a NullReferenceException. Any help is much appreciated!
Upvotes: 0
Views: 1285
Reputation: 39132
Try it this way please:
String ctlName = $"Ans{answerNum}Panel";
Panel panel = this.Controls.Find(ctlName, true).FirstOrDefault() as Panel;
if (panel != null) {
panel.BackgroundImage = Programming_Project.Properties.Resources.MutliChoiceCorrectSelected;
}
else {
MessageBox.Show("Unable to find " + ctlName);
}
Upvotes: 1
Reputation: 23
You can try to open Form1.Designer.cs where Form1 is your form name. Then find the panel code and modify it. That's how I tried and it worked.
It should look something like this:`
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// panel1
//
**this.panel1.BackColor = System.Drawing.SystemColors.ActiveCaption;**
this.panel1.Location = new System.Drawing.Point(169, 41);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(427, 190);
this.panel1.TabIndex = 0;
this.panel1.Paint += new
System.Windows.Forms.PaintEventHandler(this.panel1_Paint);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.panel1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
Upvotes: 0