【问题标题】:Send data to a user control inside another user control将数据发送到另一个用户控件内的用户控件
【发布时间】:2020-09-26 01:51:05
【问题描述】:

我需要什么

我需要 Comments UC 收集绑定到转发器的所有最新 cmets,例如 List<CommentInfo> 并通过 DataRef 属性将其发送到 Comment UC,以便我可以显示每个评论。

我尝试在Comments_ItemDataBound 中进行收集,但我无法知道我何时查看了所有数据,因为comments.Items.Count 在所有 cmets 被分配之前没有总项目数数据绑定。

int count = 1;
List<CommentInfo> commentsList = new List<CommentInfo>();
protected void comments_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        cil.Add(new CommentInfo
        {
            username = DataBinder.Eval(e.Item.DataItem, "username").ToString()
            ...
        });

        // comments.Items.Count here is 0, on next data bound will be 1 and count will be 2
        if (comments.Items.Count == 5)
        {
            var comment = e.Item.FindControl("comment1") as Comment;
            comment.DataRef = commentsList;
        }
        count++;
    }
}

这个问题要问的问题是如何创建一个所有 cmets 的 List&lt;CommentInfo&gt; 集合,以将它们传递给 DataRef 属性。


Comments 用户控制有一个中继器用于显示最新的 cmets。
转发器的DataSource 来自 SQL Server。

<asp:Repeater ID="comments" runat="server" onitemdatabound="Comments_ItemDataBound">
    <ItemTemplate>

        <uc1:Comment ID="comment1" runat="server" />

    </ItemTemplate>
</asp:Repeater>

Comment UC 将显示它从Comments 的转发器通过DataRef 类型Object 的公共属性接收到的cmets 集合中的一条评论,我将在发送之前将其转换为我需要的任何类Comment UC,至少这是我的想法。

<div class="comment" id="<%= DataRef.comment_id %>">
    <a class="comment-link" href="/<%= DataRef.friendly_url %>">
    Written by: <strong><%= DataRef.username %></strong>, <%= DataRef.comment_date %></em>
    <%= DataRef.comment_text %></a>
</div>

【问题讨论】:

  • Comment.DataRef 声明为什么类型?您绑定到中继器的类型是什么?为什么不能简单地更改一个以匹配另一个?
  • Comment.DataRef 是对象类型。 SqlDataReader 是我绑定到转发器的类型。我更新了问题。

标签: c# asp.net webforms


【解决方案1】:

一种方法是在迭代中继器时询问数据

<asp:Repeater ID="comments" runat="server">
    <ItemTemplate>    
        <uc1:Comment ID="comment1" runat="server" 
               DataRef="<%#GetMyReference(Container.DataItem)%>" />        
    </ItemTemplate>
</asp:Repeater>

以及背后的代码

public object GetMyReference(object oItem)
{
     // I am not sure what you wish to return here...
     // or you may want to full return the oItem, I am not sure
     //   this is an example
     return DataBinder.Eval(oItem, "yourDataItem");
}

请注意,DataRef 是您的用户控件上的公共值。

类似的答案:Add a list of self created web user controls to a listview in codebehind failsVirtual Listview for ASP.net?

【讨论】:

  • 我没有解释清楚所以我更新了问题。
  • @Codesmell 尝试理解并执行我在这里的建议。它可以帮助您解决问题(我阅读了您的更新,答案是一样的)...
  • 我的错误。起初我不明白。认为它的工作方式不同,所以我再次阅读了 MSDN 文档并让它工作,但这不是我需要的。我太专注于解释我想要什么,却忘了明确说出我想要什么。对此我深表歉意,因此我再次编辑了问题。
猜你喜欢
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 2015-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-25
  • 1970-01-01
相关资源
最近更新 更多