C#动态创建的LinkButton命令事件处理程序
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#动态创建的LinkButton命令事件处理程序,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2053字,纯文字阅读大概需要3分钟。
内容图文
![C#动态创建的LinkButton命令事件处理程序](/upload/InfoBanner/zyjiaocheng/651/8a06f7f779a84ba6b652e92313c49246.jpg)
所以我这里有一个奇怪的情况……我有一个System.Web.UI.WebControls.WebParts.EditorPart类.它呈现一个“搜索”按钮,当您单击该按钮时,它的clickHandler方法将进行数据库搜索,并为返回的每一行动态创建一个LinkBut??ton,设置CommandName和CommandArgument属性并添加CommandEventHandler方法,然后添加LinkBut??ton控件到页面.
问题是,当您单击LinkBut??ton时,它的CommandEventHandler方法将永远不会被调用,它看起来就像页面只是回贴到按下原始“搜索”按钮之前的位置一样.
我看到有帖子说您需要在OnLoad()或其他早期方法中添加事件处理程序,但是直到用户告诉我们要搜索的内容并单击“搜索”按钮,我的LinkBut??ton才创建.关于如何处理这个问题有什么想法吗?
谢谢!
解决方法:
这是我最喜欢的把戏:)
我们的方案是首先呈现一个控件.然后,使用来自用户的一些输入,渲染其他控件并使它们响应事件.
这里的关键是状态-您需要知道控件到达PostBack时的状态-因此我们使用ViewState.这个问题就变成了鸡与蛋的问题.直到LoadViewState()调用之后,ViewState才可用,但是您必须在调用之前创建控件才能正确触发事件.
诀窍是重写LoadViewState()和SaveViewState(),以便我们可以控制事物.
(请注意,下面的代码是粗糙的,来自内存,可能有问题)
private string searchQuery = null;
private void SearchButton(object sender, EventArgs e)
{
searchQuery = searchBox.Text;
var results = DataLayer.PerformSearch(searchQuery);
CreateLinkButtonControls(results);
}
// We save both the base state object, plus our query string. Everything here must be serializable.
protected override object SaveViewState()
{
object baseState = base.SaveViewState();
return new object[] { baseState, searchQuery };
}
// The parameter to this method is the exact object we returned from SaveViewState().
protected override void LoadViewState(object savedState)
{
object[] stateArray = (object[])savedState;
searchQuery = stateArray[1] as string;
// Re-run the query
var results = DataLayer.PerformSearch(searchQuery);
// Re-create the exact same control tree as at the point of SaveViewState above. It must be the same otherwise things will break.
CreateLinkButtonControls(results);
// Very important - load the rest of the ViewState, including our controls above.
base.LoadViewState(stateArray[0]);
}
内容总结
以上是互联网集市为您收集整理的C#动态创建的LinkButton命令事件处理程序全部内容,希望文章能够帮你解决C#动态创建的LinkButton命令事件处理程序所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。