简体   繁体   English

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

[英]Dynamically Added Event Handler Not Firing

Here is a quick code snippet, that doesn't seem to work at all for me. 这是一个快速的代码片段,对我来说似乎根本不起作用。 I'm reading from a file to create a list of radio buttons. 我正在读取文件,以创建单选按钮列表。 The problem is that when one of the radio buttons is clicked the Event Handler I have set up in the code doesn't fire. 问题是,当单击单选按钮之一时,我在代码中设置的事件处理程序不会触发。 I have tested it over and over in debug mode with line breaks... all with no luck. 我已经在调试模式下反复测试了换行符...一切都没有运气。 Am I missing something obvious here???? 我在这里想念明显的东西吗????

Thanks in Advanced! 提前致谢!

 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);

You need to add the button on every postback before events attached to it will fire. 您需要在每个回发中添加按钮,然后触发附加的事件。

If you think about it for a moment, it will make sense - if the button has not been created (on the postback), then there are no button events that can fire. 如果片刻考虑一下,这将是有道理的-如果尚未创建按钮(在回发中),则不会触发任何按钮事件。 The button must exist before events attached to it can be fired. 该按钮必须存在,才能触发与其关联的事件。

The OnInit page event is the most suitable place to add dynamic controls to a page. OnInit页面事件是将动态控件添加到页面的最合适的位置。

Read about the asp.net page life cycle . 阅读有关asp.net页面生命周期的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM