【问题标题】:Creating Generic Method to Create Controls in ASP.NET C#创建通用方法以在 ASP.NET C# 中创建控件
【发布时间】:2011-08-18 13:59:15
【问题描述】:

我正在尝试在自定义控件上生成一个方法,该方法将采用我创建的带有与控件相关的元数据的对象,并在此方法中创建控件并将其添加到页面控件集合中。下面是我创建的包含控件元数据的对象。

public class ListControlSetup
{
    public ListControl ListControl { get; set; }
    public String ControlId { get; set; }
    public String ControlCssClass { get; set; }
    public bool CausesValidation { get; set; }
    public IuIDropDownDictionary DropDownDictionary { get; set; }
    public String DropDownMethod { get; set; }
    public bool AutoPostback { get; set; }                      
}

然后我有一个将上述对象作为参数并创建控件的方法。让我们在这种情况下说一个下拉列表。假设我想为下拉列表 OnSelectedIndexchange 事件传递一个事件。我将如何以通用方式执行此操作,以便我可以在被调用的过程中连接事件。以下是我目前拥有的被调用程序。

    private void ControlSetUp(ListControlSetup control)
    {
        control.ListControl = this.CreateDropDownListControl(control.ControlId, control.ControlCssClass, control.CausesValidation);
        _myManager.DropDownMethod = control.DropDownMethod;
        _myManager.FillDropDown(control.DropDownDictionary, control.ListControl);                       
        this.Controls.Add(control.ListControl);
    }

下面是调用和对象实例化。

        ListControlSetup lcs = new ListControlSetup{ ListControl = ddlControl, DropDownMethod = SPConsts.GetData, 
                            DropDownDictionary = new DataDictionary(), ControlId="ddlControlId", ControlCssClass="inputfield", CausesValidation=false, AutoPostback=false};
        ControlSetUp(lcs);        

任何关于如何将事件添加到 ControlSetUp 方法的建议都会很好。

谢谢

【问题讨论】:

    标签: c# asp.net events controls custom-controls


    【解决方案1】:

    您的问题的解决方案是委托。 DropDownList.OnSelectedIndexChanged 事件是使用 EventHandler 类型的委托声明的(它本身在 System.dll 中声明)。因此,在您的 ListControlSetup 类中添加一个相同的 EventHandler 类型的方法,如下所示:

    public class ListControlSetup
    {
        ...
        EventHandler OnSelectedIndexChanged;  
        // Don't let the stackoverflow coloring fool you, 
        // 'OnSelectedIndexChanged' is a member variable name.
    }
    

    然后,在您的 ControlSetUp() 方法中,执行以下操作:

    if ( control.OnSelectedIndexChanged != null )
        ddlControl.SelectedIndexChanged += control.OnSelectedIndexChanged;
    

    最后,要分配 ListControlSetup 的 OnSelectedIndexChanged 列表成员,请执行以下操作:

    ListControlSetup lcs = new ListControlSetup() { ... };
    lcs.OnSelectedIndexChanged += new EventHandler( ddl_SelectedIndexChanged );
    

    当然,假设您的事件处理程序方法是 ddl_SelectedIndexChanged。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多