如何在单个 ascx 页面中使用列表框和下拉列表并在 aspx 页面中访问它

How to use a listbox and dropdown list in a single ascx page and access it an aspx page

我想在单个 ascx 页面中使用下拉列表、列表框、单选按钮列表等多个控件,而不是使用多个 ascx 页面,并且想在 aspx 页面中访问它。

假设您有一个用户控件 MyControl.ascx 具有以下控件:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl.ascx.cs" Inherits="WebApplication1.MyControl" %>
<asp:LinkButton ID="lbtn" runat="server">Link Button</asp:LinkButton>
<asp:RadioButton ID="rbtn" runat="server" Text="Radio Button" />
<asp:DropDownList ID="ddl" runat="server">
    <asp:ListItem Text="Dropdown"></asp:ListItem>
</asp:DropDownList>

现在MyControl.ascx.cs页面代码:为每个控件创建public属性并设置它们

public DropDownList 下拉列表 { get;放; }

public RadioButton radioButton { get; set; }

public LinkButton linkbutton { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    SetCtrlProperties();
}

private void SetCtrlProperties(){
    dropdown = ddl;
    radioButton = rbtn;
    linkbutton = lbtn;
}

现在,如果您将其放置在名为 default.aspx 的页面上,并希望隐藏从 .aspx 页面单击的按钮上的所有控件,则 .aspx 页面代码:

<body>
    <form id="form1" runat="server">
    <div>
    </div>
    <uc1:MyControl ID="MyControl1" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="Hide" onclick="Button1_Click" />
    </form>
</body>

和Default.aspx.cs页面代码:

protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            MyControl1.dropdown.Visible = false;
            MyControl1.radioButton.Visible = false;
            MyControl1.linkbutton.Visible = false;
        }

创建一个名为它的用户控件,并添加所有你想显示的和某些页面通用的控件。

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CustomControl.ascx.cs" Inherits="ControlsDemo.CustomControl" %>
<asp:LinkButton ID="lnkBtn" runat="server">Link Button</asp:LinkButton>
<asp:RadioButton ID="radioBtn" runat="server" Text="Radio Button" />
<asp:DropDownList ID="ddl" runat="server"></asp:DropDownList>

现在您必须在您的 aspx 页面中声明该用户控件

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ControlsDemo.aspx.cs" Inherits="ControlsDemo.ControlsDemo"%>

    <%@ Register Src="~/CustomControl.ascx" TagName="CControl" TagPrefix="ucCtrl" %>

现在您可以在该 aspx 页面的任何地方使用它

<ucCtrl="CControl" runat="server" />