2013-12-19 108 views
0

您好我有一个DataList页面:Asp.net访问DataList控件

<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文件。

我尝试使用下面的代码DataList控件来访问每个项目:

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

和dli.Dataitem是零和文本框为空为好,但在DataList acturally显示项目和shopline.ascs确实有一个TeXtBox ID是“QtyTextBox”。

任何人都可以给我一个主意吗?谢谢。

+1

凡你有这样的代码? – Adil

+0

你甚至可以放置这些代码?在检查dli.DataItem之前,通过使用快速手表来检查DataList1.Items中存在的项目和数量 –

回答

0

您需要确保您正在查看的项目是实际的数据项。使用此代码,您在for循环来检查你正在看一个实际的项目(而不是一个页脚/头/等):

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

} 

另外,我觉得你需要先得到你的用户控件。然后你可以在里面找到东西。

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

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"); 
    } 
} 
+0

是的,我发现它需要首先获取UserControl,谢谢 – simoncat

+0

@simoncat优秀!我很高兴能够提供帮助。仅供参考 - 如果此答案解决了您的问题,则可以使用复选框将其“接受”。详情请参阅[如何接受答案?](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235)。 – jadarnel27