简体   繁体   中英

Getting Control details loaded in Panel dynamically in WinForms

I have a panel in WinForms which loads panels at run time during a method call.

My code looks like:

//Adding a child panel
Panel p = new Panel();

//Adding controls to panel
Label lbl5 = new Label();
lbl5.Location = new Point(105, 3);
lbl5.Text = note.noteName;
Label lbl6 = new Label();
lbl6.Location = new Point(105, 43);
lbl6.Text = note.noteName;

p.Controls.Add(lbl5);
p.Controls.Add(lbl6);

//Adding child panel to main panel
Panel1.Controls.Add(p);

In this way whenever the method is called a new child panel will be added to main panel.

Can I Click a particular panel which is displayed in main panel ?

I want to get the value of the controls present in selected panel and show it somewhere.

I would appreciate any help on this.

Name your panel....

var pPanel = new Panel();
pPanel.Name = "pPanel";

// or write it this way....using object initializer
var pPanel = new Panel
{
   Name = "pPanel"
};

Then loop through the controls in you master panel for the control you are looking for...

 foreach(Control ctrl in mainPanel)
 {
    if (ctrl.Name.Contains("pPanel")) .... then do something etc...; 
 }

You can also search for other controls in your panels the same way ...

Subscribe to a event like so:

Panel p = new Panel();
p.Click += panel_click;

And then create the event:

private void panel_click(object sender, EventArgs e)
{
    Panel childPanel = sender as Panel;
    foreach(Control c in childPanel.Controls)
    {
        //Do something with you values...
    }
}

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