实现动态的赋予控件相应的事件比如说,我在asp.net上放置了一个button控件,但是并没有在对应的cs文件中写出它的onclick事件处理程序,但是当程序运行时,系统能判断当前的asp.net的页面是哪一页,然后判断有没有button控件,如果有的话就赋予该asp.net网页上对应的button相应的onclick事件处理程序。之所以提出这个问题是因为以前使用delphi编程时看到过这样的程序,窗体对应的事件处理程序都存放在一个公共的类中,运行时由系统判断当前的窗体有哪些控件,然后到数据库中查找对应的事件处理程序名,然后将事件处理程序赋予当前窗体上各个控件。

解决方案 »

  1.   

    用反射来做,将页面作为参数传递给你自定义的函数,然后在你的函数中通过反射获取Button,再给Button的click赋值即可。
    以前做过一个动态获取页面输入控件值的程序,没做过Button事件的,不过都差不多了,代码如下:
    public void Fill(System.Web.UI.Page page)
    {
    FieldInfo[] fields = page.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
    foreach (FieldInfo field in fields)
    {
    object outValue; if (record.TryGetValue(field.Name.ToLower(), out outValue))
    {
    object control = field.GetValue(page); System.Web.UI.ITextControl textControl = control as System.Web.UI.ITextControl;
    if (textControl != null)
    {
    textControl.Text = outValue.ToString();
    continue;
    } System.Web.UI.HtmlControls.HtmlInputControl htmlInput = control as System.Web.UI.HtmlControls.HtmlInputControl;
    if (htmlInput != null)
    {
    string type = htmlInput.Type.ToLower();
    if(type == "text" || type == "checkbox" || type == "radio" || type == "password" || type == "hidden")
    htmlInput.Value = outValue.ToString();
    continue;
    }
    }
    }
    }