在ASP.NET中对DropDownList进行子类化

我想在ASP.NET中inheritance内置的DropDownList,以便我可以为它添加function并在我的页面中使用它。 我尝试用UserControl做这个,但发现它没有公开内部DropDownList(逻辑上,我猜)。 我已经google了答案,但找不到任何东西。

我已经编写了实际的类,并且可以从DropDownListinheritance,但是我无法在ASP.NET页面中注册该文件并在源视图中使用它。 也许我错过了class上的一些房产?

有任何想法吗?

您希望在自定义控件中扩展DropDownList …而不是在usercontrol中。

创建一个名为MyLibrary的新类库项目。

添加一个名为MyDropDownList.cs的类

namespace My.Namespace.Controls { [ToolboxData("<{0}:MyDropDownList runat=\"server\">")] public class MyDropDownList: DropDownList { // your custom code goes here // eg protected override void RenderContents(HtmlTextWriter writer) { //Your own render code } } } 

编译库后,可以在Web应用程序中添加对它的引用。

和web.config中的tagprefix

   

那应该允许你将它添加到你的aspx / ascx中

  ...  

在评论中,您阐明了您的目标:“我唯一要做的就是添加一个InitialValue属性,该属性定义DDL中始终存在的第一个值。”

我认为你不需要创建一个特殊的用户控件或自定义控件来完成它。

我经常在我的网络应用程序中使用此代码来填充列表控件。 您传入一个布尔值,指示是否要在列表顶部添加其他ListItem,以及该项目的文本。

  public static void BindListControl (ListControl ctl, SqlDataReader dr, String textColumn, String valueColumn, bool addBlankRow, string blankRowText) { ctl.Items.Clear(); ctl.DataSource = dr; ctl.DataTextField = textColumn; ctl.DataValueField = valueColumn; ctl.DataBind(); if (addBlankRow == true) ctl.Items.Insert(0, blankRowText); } 

这很有用,例如,如果您希望每个DropDownList的初始值为空白,或者诸如“选择城市”之类的文本。