1

I created a function that appends buttons in a form. Buttons when clicked supposed to open different files. File paths are in listbox1. I want to add a click event for every button I append. One button should open one file from listbox1.

The part with appending buttons works, but I can't add a different event for each of them only one.

This is my code. It adds the event to every button but only the last one.

PlaySong is a function that plays ".mp3" file. That works.

Can someone help me?

int i = 0;
private void Load_Songs()
{
    List<string> url = new List<string>();
    url = listBox1.Items.Cast<String>().ToList();
    int p = 5;
    for (int j = 0; j < listBox1.Items.Count; j++)
    {
        EventHandler klik = new EventHandler(Playing);
        Song_Data titl = new Song_Data(url[j]);
        Button n = new Button
        {
            Text = titl.Title,
            Location = new Point(0, p + 20),
            Width = ClientRectangle.Width / 3,
            FlatStyle = FlatStyle.Flat
        };
        p += 20;
        n.Click += klik;
        List_Artist.Controls.Add(n);
        i++;
    }
}

private void Playing(object sender, EventArgs e)
{
    PlaySong(listBox1.Items[i].ToString());
}

1 Answer 1

1

You don't need many event handlers, just store the index to the button's Tag in your loop and then use it to find which index you should use to choose from listbox:

Button n = new Button
{      
    Text = titl.Title,
    Location = new Point(0, p + 20),
    Width = ClientRectangle.Width / 3,
    FlatStyle = FlatStyle.Flat,
    Tag = j
};

Then in your handler:

private void Playing(object sender, EventArgs e)
{
    int i= (int)((Button)sender).Tag;
    PlaySong(listBox1.Items[i].ToString());
}

to use different handler for each button you can use anonymous event handler, but won't solve your problem:

n.Click += (s, ev) =>
{
    //code when button clicked
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.