带有下拉列表的Web自定义控件

本文关键字:Web 自定义控件 下拉列表 | 更新日期: 2023-09-27 18:15:23

我正在尝试创建一个自定义web控件,上面有几个控件,一个文本框,标签和下拉列表,我想做的是在自定义控件上添加一个属性,允许在下拉列表上添加选择选项,同样的方式你会如果它只是一个正常的下拉列表,即

<asp:DropDownList ID="normalddl" runat="server">
     <asp:ListItem Text="1st value" Value="0"></asp:ListItem>
     <asp:ListItem Text="2nd value" Value="1"></asp:ListItem>
</asp:DropDownList>

我想要一个自定义控件,看起来像这样(这是一个简化版本)

<mycustomControl:ControlNamt ID="customddl" runat="server" >
   <asp:ListItem Text="1st value" Value="0"></asp:ListItem> -- how would I go about adding this in the custom control?
    <asp:ListItem Text="2nd value" Value="1"></asp:ListItem>
</mycustomControl:ControlNamt>  

带有下拉列表的Web自定义控件

不是你想要的答案。只是关于如何通过UserControls实现这一目标的建议

用户控件标记:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UC1.ascx.cs" Inherits="WebFormsScratch.UCTests.UC1" %>
<%-- Other controls here --%>
<asp:DropDownList runat="server" ID="ddl">
</asp:DropDownList>

用户后台代码:

public partial class UC1 : System.Web.UI.UserControl
{
    public IEnumerable<ListItem> DDLData;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    public override void DataBind()
    {
        ddl.DataSource = DDLData;
        ddl.DataBind();
        base.DataBind();
    }
}

aspx页面使用该控件(标记;最低限度)

<%@ Register Src="~/UCTests/UC1.ascx" TagPrefix="uc1" TagName="UC1" %>
...
...
<uc1:UC1 runat="server" ID="uc1" />

使用控件的aspx页面后面的代码

protected void Page_Load(object sender, EventArgs e)
{
    uc1.DDLData = new []
        {
            new ListItem("1st Item", "0"),
            new ListItem("2nd Item", "1"),
            new ListItem("3rd Item", "2"),
        };
    uc1.DataBind();
}