在转发器内动态设置用户控件的属性时出现编译错误



在C# Webforms网站(不是Web应用程序)中,我有以下设置:

一个页面,其中包含一个asp:Repeater的 Step.ascx。

Step.ascx 中的转发器显示此步骤中的所有部分(Section.ascx)。

SectionInfoProvider.GetSections(1).ToList()返回一个SectionInfo列表,这是一个类,包括字符串DisplayName

尝试将Section用户控件的SectionInfo属性动态设置到 Step.ascx.cs 中的转发器中时,我收到编译错误(找不到类型或命名空间名称)。我尝试使用用户控件的部分类名,UserControl,但都不起作用。

我还在尝试创建一个SectionControls集合,因为我也想将其用于页面上的其他内容。

我在这里做错了什么?

Step.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="~/Step.ascx.cs" Inherits="Custom_Step" %>
<%@ Register TagPrefix="uc" TagName="Section" Src="~/Section.ascx" %>
<asp:Repeater runat="server" ID="rptSections" OnItemDataBound="rptSections_OnItemDataBound" EnableViewState="True">
<ItemTemplate>
<uc:Section runat="server" ID="Section" EnableViewState="True"/>            
</ItemTemplate>
</asp:Repeater>

Step.ascx.cs

public partial class Custom_Step : System.Web.UI.UserControl
{
public IEnumerable<SectionInfo> Sections { get; set; }
private IEnumerable<???> SectionControls { get; set; } <-- What should ??? be?
protected override void OnLoad(EventArgs e)
{
Sections = SectionInfoProvider.GetSections(1).ToList();
rptSections.DataSource = Sections;
rptSections.DataBind();    
}
protected void rptSections_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
var info = (SectionInfo)e.Item.DataItem;
var ctrl = (???)e.Item.FindControl("Section");  <-- What should ??? be?
ctrl.SectionInfo = info;
if (SectionControls == null) SectionControls = new List<???>();  <-- What should ??? be?
((List<???>)SectionControls).Add(ctrl); <-- What should ??? be?
}    
}

Section.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="~/Section.ascx.cs" Inherits="Custom_Section " %>
<h3><asp:Literal runat="server" ID="litSectionHeading" /></h3>

Section.ascx.cs:

public partial class Custom_Section : System.Web.UI.UserControl
{
public SectionInfo SectionInfo { get; set; }
protected override void OnLoad(EventArgs e)
{
litSectionHeading.Text = SectionInfo.DisplayName;
}
} 

我认为你只需要一个类型转换和一个if。

if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {`
...
var ctrl = e.Item.FindControl<Custom_Section>("Section");`
or
var ctrl = (Section)e.Item.FindControl("Section");
...
}

这是你已经尝试过的东西吗?

可以创建动态控件,但这是一个单独的问题。

最新更新