How can I make a click on a panel do something in main, instead of a new method?
I only want it to change the text of a label that’s on my panel.

Recommended Answers

All 7 Replies

Member Avatar for stbuchok

Why not put the code that is in main into a method and then call that method in main and in the click event.

Main is a static method, hence events cannot call an instance of something to call it. So, the answer is no.

Member Avatar for stbuchok

If this is a Forms application (which it sounds like it is), what kind of code are you putting in the Main method? Should the code not be in the Form.cs file?

Leave Main for what it is. Change the text of your Label in the Clickevent handler of your Panel if you like.

Thanks for the replies.
This handler can be called by several controls. How do I refer to the proper one?
I can’t make the controls global, because some of them are declared by a recursive function - so there are multiple instances of the same control.
And when the caller is a listview - how can I determine which item was clicked?

You can have many different event handlers.
Do you use Visual Studio?
Could you show us some code?

I’m using visual studio.
Consider the following code that creates 10 panels one above the other and tells you which you’ve clicked.

int i = 10;

        public Form1()
        {
            InitializeComponent();
            Panel backPanel = new Panel();
                this.Controls.Add(backPanel);  
            backPanel.Size = new Size(50, i * 20);
            backPanel.BackColor = Color.White;
            recursivemakePanels(ref backPanel);          
        }


        private void recursivemakePanels(ref Panel panel)
        {
            Panel newPanel = new Panel();
                panel.Controls.Add(newPanel);
            newPanel.Size = new Size(50,i * 20);
            newPanel.Tag = Convert.ToString(i);
            newPanel.Click += new EventHandler(clicked);
            if (i > 0)
            {
                i = i - 1;
                recursivemakePanels(ref newPanel);
            }
        }

        private void clicked(object sender, EventArgs e)
        {
            Panel panelThatClicked = sender as Panel;
            if (panelThatClicked != null)
            {
                this.Text = "This is the panel clicked: " + panelThatClicked.Tag;
            }

        }

I’ve figured out how to tell the panels apart as you can see.
However, if I had panels, buttons, labels etc. – then the line:

Panel panelThatClicked = sender as Panel;

Wouldn’t suffice.
Any suggestions?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.