开发者

Pass index of a List to button click event sender

开发者 https://www.devze.com 2023-02-22 00:35 出处:网络
I have a List and each Button calls to the same Click function List<Button> btnList = new List<Button>;

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

精彩评论

暂无评论...
验证码 换一张
取 消