Get the index of array of picturebox clicked

前端 未结 3 638
陌清茗
陌清茗 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 21:07

    Another suggestion - create a custom class, which inherits from PictureBox. It will have an extra Index property. And you can set it between these two lines:

    txtTeamNames[i].Visible = true;
    //assign the index here
    txtTeamNames[i].Click += new EventHandler(this.clcikeventhandle);
    

    like so:

    txtTeamNames[i].Index = i;
    

    Then in the handler:

    void clickEventHandle(object sender, EventArgs e)
    { 
      PictureBox pbox = sender As PictureBox;
      int index = pbox.Index();
      string name = pbox.Name();
    }
    

    You keep the same scope of variables, which may be useful if you are concerned about it. If you are okay with upgrading scope of txtTeamNames to class level, see another answer by Hossein Narimani Rad.

提交回复
热议问题