微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Controls.Find C# Windows Form 在表单中查找现有面板

如何解决使用 Controls.Find C# Windows Form 在表单中查找现有面板

我正在制作一个表单系统,我需要在其中找到一个面板来使用字符串请求更改其背景。我使用下面的代码标签做了类似的事情,其中​​ numberEntered 是程序中的一个单独的整数。

Label label = Controls.Find($"Num{numberEntered}",true).OfType<Label>().FirstOrDefault();
label.Text = "Text"

如何为面板做类似的事情,在那里我可以在名称中使用单独的变量找到面板?如$"Panel{number}"

我已经试过了:

 Panel panel = Controls.Find($"Ans{answerNum}Panel",true).OfType<Panel>().FirstOrDefault();
 panel.BackgroundImage = Programming_Project.Properties.Resources.MutliChoiceCorrectSelected;

然而它抛出一个 NullReferenceException。非常感谢任何帮助!

解决方法

您可以尝试打开 Form1.Designer.cs,其中 Form1 是您的表单名称。 然后找到面板代码并修改它。 我就是这样尝试的,并且奏效了。

它应该看起来像这样:`

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);

    }
,

请以这种方式尝试:

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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。