如何在动态控件上附加事件 [英] How to attach events on dynamic controls

查看:58
本文介绍了如何在动态控件上附加事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的朋友们,



我在ASP.NET上的Pageload上动态创建按钮并将它们附加到表单上。当我创建按钮控件时,我需要附加一个脚本,以便在单击按钮时,它应该在同一页面上为Label设置一些值。



我能够完成上述要求,但是当单击动态按钮时,所有动态创建的按钮都会消失。甚至清除了设置到标签的值。任何人都可以帮我找到问题吗?



我尝试过:



Dear Friends,

I am creating Buttons Dynamically on Pageload in ASP.NET and attaching them to the form. When I create the button controls, I need to attach a script so that when the button is clicked, it should set some value to a Label on the same page.

I am able to complete the above requirement however, when the dynamic button is clicked, all the Dynamically created buttons are disappearing. Even the value that was set to the label is also cleared. Can any one help me to find the issue please?

What I have tried:

Button cmdBtn = new Button();

string strRowNumber = ds.Tables[0].Rows[i]["RowNumber"].ToString();
string strColumnNumber = ds.Tables[0].Rows[i]["ColumnNumber"].ToString();

cmdBtn.ID = "ABC_" + strRowNumber + "_" + strColumnNumber;
cmdBtn.Text = "ABC_" + strRowNumber + "_" + strColumnNumber;

cmdBtn.Attributes.Add("OnClick", "javascript: document.getElementById('lblSelectedButton').innerText = '" + cmdBtn.ID + "';");

frmLayout.Controls.Add(cmdBtn);

推荐答案

嗯......



首先,似乎没有人可以帮助您确定问题的位置,因为我们看不到javascript正在做什么。我建议检查一下javascript。



其次,ASP.NET提供了一种添加事件句柄的方法。请参阅:

如何:在ASP中运行时动态绑定事件处理程序。 NET Web窗体页 [ ^ ]

在ASP.Net中处理动态生成的Button,LinkBut​​ton和ImageButton的Click事件 [ ^ ]



如果要将客户端脚本事件添加到asp.net服务器控件,请阅读:如何:添加ASP.NET Web服务器控件的客户端脚本事件 [ ^ ]
Well...

First of all, seems no one can help you to identify where the issue is located, because we don't see what a javascript is doing. I'd suggest to check that javascript.

Second, ASP.NET provides a way to add event handles. Please see:
How to: Dynamically Bind Event Handlers at Run Time in ASP.NET Web Forms Pages[^]
Handle Click event of dynamically generated Button, LinkButton and ImageButton in ASP.Net[^]

If you want to add client script events to asp.net server controls, please read this: How to: Add Client Script Events to ASP.NET Web Server Controls[^]


这篇关于如何在动态控件上附加事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆