循环时无法在ListView中访问子项

时间:2012-08-08 11:54:31

标签: asp.net listview listviewitem subitem

我试图用foreach语句循环一个ListView,但我似乎无法获得项目的Subitems。 For语句也没有成功。 IntelliSense不会在两种方式上提出建议。

代码背后:

protected void btnNext_Click(object sender, EventArgs e)
{
    foreach (ListViewItem item in ListView1.Items)
    {
       item. *(here a should get the Subitems)*

    }
}

ASPX

<asp:ListView ID="ListView1" runat="server" DataSourceID="ObjectDataSource1">
    <LayoutTemplate>
      <table>
        <tr>
            <th>Customer</th>
            <th>Item No</th>
        </tr>
         <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
      </table>   
    </LayoutTemplate>
    <ItemTemplate>    
            <tr>     
                <td>
                    <%# Eval("CustomerName") %>
                </td>
                <td>
                    <%# Eval("Item") %>
                </td>
            </tr> 
    </ItemTemplate>
    </asp:ListView>

3 个答案:

答案 0 :(得分:0)

你应该使用循环listview.items

for (int j = 0; j < this.listView1.Items.Count; j++) 
            { 
                ListViewItem item = 
                    (ListViewItem)this.listView1.ItemContainerGenerator.ContainerFromIndex(j); 

            } 

答案 1 :(得分:0)

Get data being bound to ListView on DataBound event

您可以像处理listView1_ItemDataBound事件中那样处理循环内部的代码。

答案 2 :(得分:0)

你必须改变你的aspx页面如下

<asp:ListView ID="ListView1" runat="server" DataSourceID="ObjectDataSource1">
<LayoutTemplate>
  <table>
    <tr>
        <th>Customer</th>
        <th>Item No</th>
    </tr>
     <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
  </table>   
</LayoutTemplate>
<ItemTemplate>    
        <tr>     
            <td>
             <asp:Label ID="lblCustomerName" Text='<%# Eval("CustomerName") %>'  runat="server"></asp:Label> 
            </td>
            <td>                    
             <asp:Label ID="lblItem" Text='<%# Eval("Item") %>' runat="server"></asp:Label> 
            </td>
        </tr> 
</ItemTemplate>
</asp:ListView>

现在你必须在文件

后面的代码中使用如下所示的每个循环
string strProductNames = string.Empty;
foreach (ListViewItem item in ListView1.Items)
    {
        Label lblCustomerName= (Label)item.FindControl("lblCustomerName");

       // strProductNames = strProductNames + lblCustomerName.Text + "<br/>";
       // you can get values in lblCustomerName.Text. use this value as per your   requirement
    }

希望这会帮助你......快乐的编码

相关问题