Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

c# - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...