三个ImageButtons下面是在页面的代码隐藏添加到面板(pBreakfast):事件处理程序停止工作,处置后
ImageButton ibSR = new ImageButton();
ibSR.ID = "ibStickyRoll";
ibSR.ImageUrl = "/images/Breakfast.gif";
ibSR.Click += new ImageClickEventHandler(ImageButton_Click);
pBreakfast.Controls.Add(ibSR);
ImageButton ibD = new ImageButton();
ibD.ID = "ibDoughnut";
ibD.ImageUrl = "/images/Breakfast.gif";
ibD.Click += new ImageClickEventHandler(ImageButton_Click);
pBreakfast.Controls.Add(ibD);
ibD.Dispose();
using(ImageButton ibC = new ImageButton()){
ibC.ID = "ibCrepe";
ibC.ImageUrl = "/images/Breakfast.gif";
ibC.Click += new ImageClickEventHandler(ImageButton_Click);
pBreakfast.Controls.Add(ibC);
}
我希望要么所有三个会的工作,或者是被处置ImageButtons会产生一个错误或根本不出现。但是,发生的事情是所有三个都出现了,并且不会导致任何错误,但事件处理程序从不会为处理的ImageButton触发。
为什么配置只导致事件处理程序连接消失?
我动态地将TableRow和TableCell添加到同一页上的表中,并将ImageButton放置在每行的一个单元中。我对TableRow和TableCell使用'using'没有任何问题。外部(TableRow & TableCell)对象被丢弃似乎没有问题;只要我不会处理动态ImageButton,事件处理程序就会在点击时触发OK。
在这种情况下,是否可以永不处理ImageButton?我已经将StackOverflow的建议放在心上,并尝试在我所有的一次性对象上使用using(),所以这真的让我感到困扰。
谢谢!
感谢您的回复,Moby。不过,我不禁想到除此之外还有更多。即使在pBreakfast中有refing,dispose()也会立即发生吗?我认为pBreakfast.controls中的新ImageButton现在属于pBreakfast,并且在pBreakfast清理之前不会发生配置。这对我来说很混乱。如果我不应该在.Add()之后处理它,为什么ImageButton是一次性的? 另外,这个解决方案没有一个designer.cs(至少我找不到),我在服务器上使用按需编译。 :^) –
处置不会立即发生。只有在显式调用Dispose()时才会发生。当您说pBreakfast.controls中的新ImageButton现在属于pBreakfast并且在pBreakfast清理之前不会发生处理时,您是正确的。这正是你想要的。在ImageButton上调用Dispose()之后,ImageButton就没用了。死。过时了。你不想创建一个ImageButton,把它给pBreakfast,然后摧毁它! ImageButton是一次性的,因此可以在表单完全消失后将其清理干净。 –
另外,我是一个doof,错过了这是ASP.NET不WinForms。对于那个很抱歉。但它仍然存在:不要在别人正在使用它的时候处理这个对象。 –