Pass index of a List to button click event sender
I have a List and each Button calls to the same Click function
List<Button> btnList = new List<Button>;
// function to add a new button
Button btn = new Button();
btn.Click += showIndex_Click;
btnList.Add(btn);
private void showIndex_Click(object sender, Rou开发者_Go百科tedEventArgs e)
{
MessageBox.Show(???);
}
The click event will display the index of the sender Button. How can I do that?
The sender parameter is the Button who fired the event. You can use it to search in the list and find its index.
var button = sender as Button;
var index = btnList.IndexOf(button);
here clickbtn will store all the informattion about the button that is clicked.
So you can get the index about that button
private void showIndex_Click(object sender, RoutedEventArgs e)
{
Button clickbtn = sender as Button;
MessageBox.Show(???);
}
精彩评论