Can't access Subitems in ListView while looping

不打扰是莪最后的温柔 提交于 2019-12-24 19:40:05

问题


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>

回答1:


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




回答2:


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

            } 



回答3:


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.



来源:https://stackoverflow.com/questions/11863956/cant-access-subitems-in-listview-while-looping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!