简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM