How to retrieve the value of a ListView item in the same row as a LinkButton

I have a dynamically generated ListView which displays a set of groups, retrieved from a database. The ListView template looks like this:

<asp:ListView ID="lvGroups" runat="server">
        <ItemTemplate>
            <tr>
                <td>
                    <asp:Label ID="lblGroupName" runat="server" Text='<%# Eval("GroupName") %>' />
                </td>
                <td>
                    <asp:LinkButton ID="lnkRemove" runat="server" Text="Remove" OnClick="lnkGroupRemove" OnClientClick="Confirm()" />
                </td>
            </tr>

        </ItemTemplate>
    </asp:ListView>

As you can see, there is a value, which is pulled from a database, and then a linkbutton for removing that value. When the linkbutton is clicked, it displays a javascript confirmation message, and if you click Yes on that message, then that specific entry will be removed from the database.

Unfortunately I cannot simply remove the GroupName where the ID = row number, because you can both add and remove groups, so that will quickly become inconsistent.

All I truly need is a way to retrieve the GroupName from the same row as the linkbutton that was clicked, if I can figure out how to do that, then I can easily configure a database query to successfully remove the entry. If you have another solution, however, that is also great.

I’m sad to say that I have no example code for the lnkGroupRemove event, as I simply have no clue where to start on this problem.

Any help on this subject would be much appreciated!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use the DataKeyNames attribute:

<asp:ListView ID="lvGroups" runat="server" DataKeyNames="ID,GroupName" >

and get the value this way in code-behind:

protected void lnkGroupRemove(object sender, EventArgs e)
{
    ListViewItem item = (sender as LinkButton).NamingContainer as ListViewItem;
    int ID = (int)lvGroups.DataKeys[item.DataItemIndex].Values["ID"];
    string groupName = (string)lvGroups.DataKeys[item.DataItemIndex].Values["GroupName"];
}

I added an ID value to show that additional fields can be added to DataKeyNames and retrieved from code-behind, including fields that are in the data source but not displayed in the ListView.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x