如何动态创建按钮并添加不同的事件处理程序



我创建了一个函数,在表单中添加按钮。单击按钮可以打开不同的文件。文件路径在列表框1中。我想为我附加的每个按钮添加一个点击事件。一个按钮可以打开列表框1中的一个文件。

带有附加按钮的部分可以工作,但我不能为每个按钮添加不同的事件——只有一个。

这是我的密码。它将事件添加到每个按钮,但仅添加到最后一个按钮。

PlaySong是一个播放.mp3文件的功能。这很管用。

有人能帮我吗?

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

您不需要太多的事件处理程序,只需将索引存储到循环中按钮的Tag,然后使用它来查找您应该使用哪个索引从列表框中进行选择:

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

然后在您的处理程序中:

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

要为每个按钮使用不同的处理程序,可以使用匿名事件处理程序,但不能解决您的问题:

n.Click += (s, ev) =>
{
//code when button clicked
};

最新更新