【问题标题】:Asp.net access DataListAsp.net 访问 DataList
【发布时间】:2013-12-20 00:33:21
【问题描述】:

您好,我在页面中有一个数据列表:

<asp:DataList ID="DataList1" runat="server" BackColor="White" Width="98%" HorizontalAlign="Center" CellPadding="7" >
    <ItemTemplate>
        <uc1:ShopLine id="ShopLine1" runat="server" DataItem='<%# Container.DataItem %>' 
                                        ShopListLineId='<%# DataBinder.Eval(Container.DataItem, "ShopListLineID") %>'
                                        OnDataUpdated="ShopLine1_DataUpdated">
        </uc1:ShopLine>
    </ItemTemplate>
    <SeparatorStyle Width="1px" />
   <ItemStyle CssClass="listItem1" />
</asp:DataList>

Shopline 是一个 ascx 文件。

我试图使用以下代码来访问数据列表中的每个项目:

 foreach (DataListItem dli in DataList1.Items)
             {
                 string productId = DataBinder.Eval(dli.DataItem, "ProductID").ToString();
                 TextBox tb = (TextBox)dli.FindControl("QtyTextBox");
             }

dli.Dataitem 为空,textbox 也为空,但数据列表实际显示项目,shopline.ascs 确实有一个 TeXtBox id 为“QtyTextBox”。

谁能给我一个想法?谢谢。

【问题讨论】:

  • 你在哪里有这个代码?
  • 你把这段代码放在哪了?在检查 dli.DataItem 之前,使用快速手表检查 DataList1.Items 中存在哪些项目以及有多少项目

标签: c# asp.net


【解决方案1】:

您需要确保您正在查看的项目是实际的 DataItem。在您的 for 循环中使用此代码来检查您是否正在查看实际项目(而不是页脚/页眉/等):

if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{

}

另外,我认为您需要先获取 UserControl。然后你就可以在里面找到东西了。

您的最终产品将是这样的:

foreach (DataListItem dli in DataList1.Items)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        string productId = DataBinder.Eval(dli.DataItem, "ProductID").ToString();

        // Find the UserControl that's in this DataListItem
        ShopLine myShopLine = (ShopLine)dli.Findcontrol("ShopLine1");
        //Then extract the information you need from it
        TextBox tb = (TextBox)myShopLine.FindControl("QtyTextBox");
    }
}

【讨论】:

  • 是的,我发现我需要先获取 UserControl,谢谢
  • @simoncat 太棒了!我很高兴能帮上忙。仅供参考 - 如果此答案解决了您的问题,您可以使用复选标记框“接受”。详情请见How does accepting an answer work?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-07
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多