动态添加的事件处理程序不会触发

这是一个快速的代码片段,对我来说似乎根本不起作用。 我正在从文件中读取以创建单选按钮列表。 问题是当单击其中一个单选按钮时,我在代码中设置的事件处理程序不会触发。 我已经在调试模式下一遍又一遍地测试了它,并且没有运气。 我错过了一些明显的东西????

提前致谢!

strLine = strLine.Trim(); System.Diagnostics.Debug.WriteLine("[3-a] ship by date - date: " + strLine); try{ shipByDate = (Convert.ToDateTime(strLine)); } catch (Exception e) { shipByDate = new DateTime(); } shipByDesc = sr.ReadLine().Trim(); System.Diagnostics.Debug.WriteLine("[3-b] ship by date - desc: " + shipByDesc); RadioButton button = new RadioButton(); button.Text = shipByDesc + " - " + shipByDate.ToString("MM/dd/yyyy"); button.Checked = false; button.GroupName = "shipByOptions"; button.ID = "shipByRadio" + count; //button.EnableViewState = true; button.AutoPostBack = true; button.CheckedChanged += new EventHandler(shipBy_CheckedChanged); // <-- doesn't work!!! //form1.Controls.Add(button); shipByPlaceHolder.Controls.Add(button); 

您需要在每个回发时添加按钮,然后才会触发附加到它的事件。

如果你考虑一下,它会有意义 – 如果没有创建按钮(在回发上),那么就没有可以触发的按钮事件。 该按钮必须存在才能触发附加到它的事件。

OnInit页面事件是最适合向页面添加动态控件的位置。

阅读asp.net页面生命周期 。