从ListView控件获取索引项

时间:2012-09-17 12:17:18

标签: c# asp.net listview

ASPX

<asp:SqlDataSource ID="SqlDataSource5" runat="server" 
       ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
       SelectCommand="SELECT * FROM [Themes] WHERE ([Theme] = @Theme) ORDER BY [Price]">
       <SelectParameters>
            <asp:Parameter DefaultValue="Dubai-and-Beyond" Name="Theme" Type="String" />
       </SelectParameters>                                   
</asp:SqlDataSource>
<asp:ListView ID="theme5" runat="server" DataSourceID="SqlDataSource5">
      <LayoutTemplate>
             <div id="itemPlaceHolderContainer" runat="server">
                 <span id="itemPlaceHolder" runat="server"></span>
             </div>
       </LayoutTemplate>
<ItemTemplate>
    <div>
       <asp:Image ID="Destinationimage" runat="server"
        ImageUrl='<%# Eval("ID", "~/CMS/ThemesHandler.ashx?ID={0}")+"&img=1"%>'  
        AlternateText="Destination_Image"  Height="140px" Width="179px" />
       <asp:Label ID="lblcountry" runat="server" Text='<%#Eval("Country") %>' />
   </div>                                                                                           
   <div class="hotel_name">                                                            
       <asp:Label ID="lblcountry" runat="server" Text='<%#Eval("Country") %>' /></div>
       <asp:ImageButton ID="imgbtn5" runat="server" ImageUrl="images/book_nw.png"  
            OnClick="imgbtn5_Click" AlternateText="get_quote"/></div>
    </ItemTemplate>
    </asp:ListView>

代码

protected void imgbtn5_Click(object sender, EventArgs e)
{        
    ListViewItem item = theme5.Items[0];
    Label country = (Label)item.FindControl("lblcountry");
    string con = country.Text.ToString();
    Session["country"] = con.ToString();
    Response.Redirect("Get_Quote.aspx");
}

这里,Theme5是Listview。每个listview项目中都有一个Label和imgbutton。 我想在imgbutton click事件上传输标签值。 这里的问题是我无法识别listview项的Row索引。

1 个答案:

答案 0 :(得分:0)

您可以在ListView中使用ImageButton的CommandNameCommandArgument。您可以在ItemCommand事件中访问相应的项目。

<asp:ImageButton ID="imgbtn5" runat="server" ImageUrl="images/book_nw.png"  
        OnClick="imgbtn5_Click" AlternateText="get_quote"
        CommandName="YOUR_COMMAND_NAME" 
        CommandArgument='<%#Eval("ANY_COLUMN_OF_SOURCE") %>' />

在你的codeBehind文件中

protected void theme5_OnItemCommand(object sender, ListViewCommandEventArgs e)
{
  if (String.Equals(e.CommandName, "YOUR_COMMAND_NAME"))
  {
   string arg = e.CommandArgument; // do whatever you want
   ListViewDataItem dataItem = (ListViewDataItem)e.Item;

 }
}