MouseDown event of dynamically created panels

nandithaa
nandithaa used Ask the Experts™
on
Hi.....
I have many dynamically created panels on a Form. When the user clicks any panel, how can i identify which panel the user clicked?

Thanks in advance.....
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
You may try to add a number flag for each panel when created or try hash code.

Author

Commented:
But on MouseClick  event how can i understand which panel user clicked?
Can you give me a small example with code?
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Retired
Distinguished Expert 2017
Commented:
Hi nandithaa;

You can assign a unique name to each panel and then in the MouseClick event get the reference to which panel was clicked on and extract the name of the panel. See code snippet for an example.

Fernando
private void button1_Click(object sender, EventArgs e)
{
    // Create the panel dynamically 
    Panel p = new Panel();
    // Assign a unique name to the panel 
    p.Name = "TestPanel1";
    // Add a click event handler to the panel
    // ... Initialize other properties
    p.Click += new EventHandler(panel_Click);
    // Assign the panel to be the child of another control
    // in this case it is the form
    this.Controls.Add(p);
}

void panel_Click(object sender, EventArgs e)
{
    // The parameter sender is te panel that was clicked on
    // cast it to a type Panel
    Panel p = (Panel)sender;

    // Execute the code for the panel that was clicked on
    switch (p.Name)
    {
        case "TestPanel1":
            MessageBox.Show("My name is " + p.Name);
            break;
    }            
}

Open in new window

use the object sender and flag proporty together

when you click on an panel with the mouse the object sender is now that panel. you just need to cast sender to a Panel to access all its proporties.
((Panel)sender).tag;
((Panel)sender).Name;
((Panel)sender).Container.Add();

Open in new window

Author

Commented:
Thanks :)
Fernando SotoRetired
Distinguished Expert 2017

Commented:
Not a problem, glad to help.  ;=)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial