MouseDown event of dynamically created panels

nandithaa used Ask the Experts™
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.....
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.


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.

Distinguished Expert 2017
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.

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

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

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.

Open in new window


Thanks :)
Fernando SotoRetired
Distinguished Expert 2017

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