Question

I am trying to loop over a ListView with a foreach statement, but I can't seem to get the Subitems of item. No success with a For statement either. IntelliSense doesn't propose it on both ways.

Code Behind:

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>
Was it helpful?

Solution

you have to change your aspx page as below

<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>

Now you have to use for each loop as below in code behind file

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
    }

Hope this will helps you..happy coding

OTHER TIPS

you should use loop throug listview.items

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

            } 

Get data being bound to ListView on DataBound event

you would treat the code inside of your loop the same way that it would be handled inside of the listView1_ItemDataBound event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top