单击时从LinkBut​​ton获取ListViewItem

时间:2019-05-19 13:00:54

标签: c# asp.net .net

我有一个这样的ASPX页面

<asp:ListView ID="lv" runat="server">
    <ItemTemplate>
        <asp:LinkButton ID="lvLB" OnClick="lvLB_OnClick" runat="server">ButtonLabel</asp:LinkButton>
    </ItemTemplate>
</ListView>

然后是ASPX.cs文件:

protected void lvLB_OnClick(object sender, EventArgs e){
    LinkButton lb = (LinkButton)sender;
    ListViewDataItem data = (ListViewDataItem)lb.Parent;
    DataRowView rV = data.DataItem as DataRowView;
}

列表视图已正确绑定了DataSet对象,并且确实在页面上显示了正确的数据。

我试图获取单击按钮的Item的DataRowView,但是上面的内容将在data.DataItem处返回null作为DataRowView。

我错过了什么?

2 个答案:

答案 0 :(得分:0)

仅当基础类型为DataItemDataRowView时,才能将DataView强制转换为DataTable。否则,它不能立即转换。您的组件是ListView,因此如果需要DataRowView,则必须自己进行映射。

答案 1 :(得分:0)

您可以使用OnSelectedIndexChanged事件通过Select命令按钮获取行数据:

<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
            <ItemTemplate>
                <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
    </Columns>
</asp:GridView>

隐藏代码:

protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
    //Accessing BoundField Column
    string name = GridView1.SelectedRow.Cells[0].Text;

    //Accessing TemplateField Column controls
    string country = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text;

    lblValues.Text = "<b>Name:</b> " + name + " <b>Country:</b> " + country;
}

这是完整的示例和演示:

https://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx