0

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.

4
Contributors
7
Replies
8
Views
5 Years
Discussion Span
Last Post by ispiro
0

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

0

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

0

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?

0

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

0

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?

Edited by ispiro: n/a

0

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

0

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?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.