@YeP95 (ななは には)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

追加するパネル名を引数で設定する

解決したいこと

コンボボックスをパネルに追加する際、定数にパネル名を入れ、それを引数として受け取り、追加するパネルを判別したいのですがうまくいきません。(上手に説明できなくてすみません)

発生している問題・エラー

'string' に 'Constrols' の定義が含まれておらず、型 'string' の最初の引数を受け付けるアクセス可能な拡張メソッド 'Constrols' が見つかりませんでした。using ディレクティブまたはアセンブリ参照が不足しています。

例)

pname.Controls.Add(comboBox);

または、問題・エラーが起きている画像をここにドラッグアンドドロップ

該当するソースコード

c#```
using System;
using System.Windows.Forms;
using System.Drawing;

class FormMain : Form
{
    const string p1 = "panel1";
    const string p2 = "panel2";

    Panel panel1;


    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new FormMain());
    }

    FormMain()
    {

        Text = "Button Click Sample";
        ClientSize = new Size(600, 400);
        Button btn1 = new Button();
        btn1.Location = new Point(50, 50);
        btn1.Text = "Create Panel";
        btn1.Click += btn1_Click;
        Controls.AddRange(new Control[] { btn1 });

        this.Controls.Add(panel1);  

    }

    public void  CreateMyPanel( string pname )
    {
        panel1 = new Panel();
        Panel panel2 = new Panel();

        // Initialize the Panel control.
        panel1.Location = new Point(56, 72);
        panel1.Size = new Size(264, 152);

        // Initialize the Panel control.
        panel2.Location = new Point(356, 72);
        panel2.Size = new Size(264, 152);

        // Set the Borderstyle for the Panel to three-dimensional.
        panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
        panel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;

        // Add the Panel control to the form.
        this.Controls.Add(panel1);
        this.Controls.Add(panel2);

        ComboBox comboBox = new ComboBox();
        comboBox.Items.Add("A");
        comboBox.Items.Add("B");
        comboBox.Items.Add("C");
        comboBox.Items.Add("D");
        comboBox.Items.Add("E");

        pname.Controls.Add(comboBox);

    }

    void btn1_Click(object sender, System.EventArgs e)
    {
        CreateMyPanel(p1);
        CreateMyPanel(p2);

    }
}

自分で試したこと

訳あってif文は使えないため、↓の方法以外でお願いいたします・
if (pname = p1 )
{panel1.Controls.Add(comboBox)}
else
{panel2.Controls.Add(comboBox)}

0 likes

No Answers yet.

Your answer might help someone💌