Reputation: 381
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!
Upvotes: 1
Views: 1589
Reputation: 73761
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.
Upvotes: 2