在ASP.NET中对DropDownList进行子类化
-
04-07-2019 - |
题
我想在ASP.NET中继承内置的DropDownList,以便我可以为它添加功能并在我的页面中使用它。我尝试用UserControl做这个,但发现它没有暴露内部DropDownList(逻辑上,我猜)。我已经google了答案,但找不到任何东西。
我已经编写了实际的类,并且可以从DropDownList继承子类但我无法在ASP.NET页面中注册该文件并在源视图中使用它。也许我错过了班上的一些房产?
有什么想法吗?
解决方案
您希望在自定义控件中扩展DropDownList ...而不是在用户控件中。
创建一个名为MyLibrary的新类库项目。
添加一个名为MyDropDownList.cs的类
namespace My.Namespace.Controls
{
[ToolboxData("<{0}:MyDropDownList runat=\"server\"></{0}:MyDropDownList>")]
public class MyDropDownList: DropDownList
{
// your custom code goes here
// e.g.
protected override void RenderContents(HtmlTextWriter writer)
{
//Your own render code
}
}
}
编译库后,可以在Web应用程序中添加对它的引用。
web.config中的tagprefix
<add tagPrefix="my" namespace="My.Namespace.Controls" assembly="MyLibrary" />
这应该允许你将它添加到你的aspx / ascx的
<my:MyDropDownList ID="myDDl" runat="server">
...
</my:MyDropDownList>
其他提示
在评论中,您阐明了您的目标:“我唯一要做的就是添加一个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的初始值为空白,或者诸如“选择城市”之类的文本。
不隶属于 StackOverflow