Get the index of array of picturebox clicked

前端 未结 3 644
陌清茗
陌清茗 2021-01-25 20:14

I am creating some picturebox dynamically and click event for picturebox as follows

Image myImage = Image.FromFile(\"image/Untitled6.png\"); 
PictureBox[] txtTea         


        
3条回答
  •  无人共我
    2021-01-25 20:46

    You can access the PictureBox via the sender argument. So try this:

    PictureBox[] txtTeamNames;
    
    void YourMethod()
    {
        Image myImage = Image.FromFile("image/Untitled6.png"); 
        txtTeamNames = new PictureBox[5];        
        //The same as your code
    }   
    
    void clcikeventhandle(object sender, EventArgs e)
    {          
        int index = txtTeamNames.IndexOf(sender As PictureBox);
    }
    

    EDIT: Approach #2

    But if you are not happy with declaring that array in the class scope you can try this approach:

    //Same as your code
    for (int i = 0; i < txtTeamNames.Length; i++)
    {
        //Save as your code
        txtTeamNames[i].Tag = i;                        // ADD THIS LINE
    }
    

    Then:

    void clcikeventhandle(object sender, EventArgs e)
    {            
        int index = int.Parse((sender as PictureBox).Tag.ToString());
    }
    

提交回复
热议问题