我想要一个相册,当我点击任何图片时,它会转到另一个表格来编辑该图片.
现在我在表格中有一些图片框,名称如PB0,PB1,PB2,……
和这样的方法
private void msgShow(int id) { MessageBox.Show(id.ToString()); }
PB11.Click += new EventHandler((sender2,e2) => msgShow(3)); PB12.Click += new EventHandler((sender2,e2) => msgShow(4));
当我单击PictureBox1(PB1)时,messageBox显示
3
当我点击PictureBox2(PB2)时,messageBox显示
4
这是真的,因为我添加了18个新的pictureBox并使用此代码来做到这一点
for (int i = 0; i <= 19; i++) { ((PictureBox)Form2.ActiveForm.Controls.Find("PB" + i,true)[0]).Click += new EventHandler((sender2,e2) => msgShow(i)); }
现在它的错误,当我点击每个pictureBox messageBox显示
20
解决方法
试试这个.用这个替换你的for循环
for (int i = 0; i <= 19; i++) { var pictureBox = (PictureBox) Form2.ActiveForm.Controls.Find("PB" + i,true)[0]; pictureBox.Tag = i; pictureBox.Click += (sender,args) => { msgShow((int)((sender as PictureBox).Tag)); }; }
编辑:根据新的评论,发送类对象为
for (int i = 0; i <= 19; i++) { var pictureBox = (PictureBox) Form2.ActiveForm.Controls.Find("PB" + i,true)[0]; var productInfo = new ProductInfo { //This class is not mentioned into the question so I set example properties here eg. ImageName = "MyImage1.png",ImagePath = "C:\\Images\\" ... }; pictureBox.Tag = productInfo; pictureBox.Click += (sender,args) => { msgShow((ProductInfo)((sender as PictureBox).Tag)); }; }
现在你的msgShow将采用ProductInfo对象i-e
private void msgShow(ProductInfo pr) { using(var fr = new FormProduct()) { fr.pInfo = pr; fr.showDialog(); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。