简体   繁体   中英

Manipulating dynamic controls c# form application

In an application there are panels made at run time. In order to access the panel named myTestPanel I use controls.find, which makes an array that I have to loop through. Is there a better way? Can I publicly declare some panels by name so that I can just manipulate the name as though they were added through the form designer?

This is my code inside of the namespace.

    private void mnuForm_Shown(object sender, EventArgs e)
    {
        Panel myTestPanel = new Panel();
        myTestPanel.Top = 0;
        myTestPanel.Left = 0;
        myTestPanel.Width = this.Width;
        myTestPanel.Height = this.Height;
        myTestPanel.Dock = DockStyle.Fill;
        myTestPanel.BackColor = System.Drawing.Color.Gold;
        myTestPanel.Name = "myTestPanel";
        myTestPanel.Click += new EventHandler(myTestPanel_Click);
        Controls.Add(myTestPanel);
        myTestPanel.Show();
    }

    private void myTestPanel_Click(object sender, EventArgs e)
    {
        var myTestPanel = Controls.Find("myTestPanel", true);
        foreach (var ReallyStupidWayToDoThis in myTestPanel)
        {
            Controls.Remove(ReallyStupidWayToDoThis);
            ReallyStupidWayToDoThis.Dispose();
        }

You can declare an array of Panel, then loop through that array to add each pannel into UI And when you want to access one of them, just access it through the array. By this way, you don't have to "Find" the control, but directly access it through Index of array.

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