[英]How do I programmatically assign a on click event to a bullet list which was programmatically created?
I tried to programtically write a method and assign it as a method called upon a onclick event, but something isn't right here. 我试图以编程方式编写一个方法,并将其分配为在onclick事件上调用的方法,但是此处不正确。 The method isn't called. 该方法未调用。
BulletedList bulletList = new BulletedList();
I added items into the bullet list using bulletList.Items.Add(...);
我使用bulletList.Items.Add(...);
将项目添加到项目符号列表中
I tried to programtically assign a bulletList_Click method with bulletList.Click += new BulletedListEventHandler(bulletList_Click);
我试图以编程方式将bulletList_Click方法分配给bulletList.Click += new BulletedListEventHandler(bulletList_Click);
This is the method which is supposed to be triggered off 这是应该触发的方法
void bulletList_Click(object sender, BulletedListEventArgs e) { //codes here } void bulletList_Click(object sender,BulletedListEventArgs e){//此处编码}
Unless you've created a special class of your own for handling events you're probably just looking for: 除非您已经创建了自己的特殊类来处理事件,否则您可能只是在寻找:
bulletList.Click += new EventHandler(bulletList_Click);
bulletList.Click + =新的EventHandler(bulletList_Click);
Edit: 编辑:
You've got your command in there correctly, actually. 实际上,您的命令正确无误。 However, reading your comment above that it is programmatically created, I have an update: 但是,阅读上面的评论(它是通过程序创建的)后,我进行了更新:
In order to register an event for an object that is programmatically created, the event must be created and added to a control on the page during the Page_Init
event. 为了注册以编程方式创建的对象的事件,必须在Page_Init
事件期间创建该事件并将其添加到页面上的控件中。 If this doesn't happen, the object will not be added to the viewstate and no events will be catchable. 如果这种情况没有发生,则该对象将不会添加到viewstate中,也不会捕获任何事件。
Edit 2: 编辑2:
Here is an article on 4GuysFromRolla that helped me accomplish this the last time I needed it. 这是有关4GuysFromRolla的文章,它在我上一次需要它时帮助我完成了此任务。 Here is the followup article for it indicating why the Page_Init event is appropriate based on the need to have the control in the ViewState. 这是它的后续文章 ,根据需要在ViewState中放置控件,指示为什么Page_Init事件是适当的。 I have seen elsewhere in other forums that this can be circumvented by making sure that for each postback the controls are added identically to the last time the page was loaded, but I have not verified that functionality. 我在其他论坛的其他地方看到过,可以通过确保为每个回发将控件添加到与上次加载页面相同的方式来绕过此问题,但是我尚未验证该功能。
Have you tried to have the Event Handler automatically generated from the drag-and-drop interface of Visual Studio? 您是否尝试过从Visual Studio的拖放界面自动生成事件处理程序? Like selecting the control, selecting the Click event from the events list on the right and then just writing the code inside the generated handler? 就像选择控件一样,从右侧的事件列表中选择Click事件,然后将代码写入生成的处理程序中?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.