I am currently coding a file browser in C# and I've never used C# before. I'm trying to make a list of files that will become active (ie: change skin) when I click on one. The problem is that I have no idea how to do so.

Current implementation:
Added buttons for each file in the directory inside loop and change skin to look like labels.

Desired:
Buttons will change skin when clicked on.

I think I should be writing an event handler but I don't know how to add an event handler to a button that is declared inside a loop. Help please?

Recommended Answers

All 3 Replies

Here is how you assign an event handler programatically (my example assigns an event handler to the Button.Click event):

public void SetupButton()
{
  Button myButton = new Button();
  // assign the event handler
  myButton.Click += new EventHandler(myButton_click);
}

// definition for the event handler code
// note that the signature for this method must match the Click delegate signature
private void myButton_click(object sender, EventArgs e)
{
   // here you put the code for performing a task when the button is clicked

}

Hope this helps :)

Of course, if you declare the button like darkagn did and then not assign it to the form, you'll never see it :)

Lol, very true, well spotted :$

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.