单击列表视图中的按钮时获取单元格值

时间:2018-08-02 02:40:01

标签: c# asp.net

我创建一个列表视图,并将按钮放在表格单元格的每一行中。在按钮单击事件中,如何获取表中的值,例如Aitline,ArrCity或项目索引。

// aspx

<asp:ListView ID="ListView1" runat="server">
    <LayoutTemplate>
        <ul>
            <asp:PlaceHolder ID="itemPlaceholder" runat="server" />    
        </ul>                
    </LayoutTemplate>
    <ItemTemplate>
        <li>
            <table class="table table-condensed table-striped table-hover">
                <th><%#Eval("Airline")%></th>
                <th><%#Eval("DepCity")%></th> 
                <th><%#Eval("DepTime")%></th> 
                <th><%#Eval("FlyTime")%> 分鐘</th> 
                <th><%#Eval("ArrTime")%></th> 
                <th><%#Eval("ArrCity")%></th> 
                <th class="success"><%#Eval("TotalFare")%></th>
                <th><asp:Button type="submit" class="btn btn-primary btn-lg" id="PayButton" runat="server" Text="Pay" OnClick="PayButton_OnClick"/></th>
            </table>
        </li>
    </ItemTemplate>
    <EmptyDataTemplate>
        <p>Nothing here.</p>
    </EmptyDataTemplate>
</asp:ListView>

//在PayButton中的C#单击事件中

protected void Page_Load(object sender, EventArgs e)
{
    List<Ticket> TicketList = new List<Ticket>();

    this.ListView1.DataSource = TicketList;
    this.ListView1.DataBind();
}

protected void PayButton_OnClick(object sender, EventArgs e)
{
    // how to get table cell value here?
}

1 个答案:

答案 0 :(得分:1)

您可以使用DataKeyNames属性。例如:

<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID, Name" >

,然后在代码隐藏中以这种方式获取值:

protected void PayButton_OnClick(object sender, EventArgs e)
{
    ListViewItem item = (sender as LinkButton).NamingContainer as ListViewItem;
    int id = (int)ListView1.DataKeys[item.DataItemIndex].Values["ID"];
    string name = (string)ListView1.DataKeys[item.DataItemIndex].Values["Name"];
}