C# ListView:按它删除一行';单击按钮时的所有者

C# ListView:按它删除一行';单击按钮时的所有者,c#,asp.net,listview,C#,Asp.net,Listview,我有一个列表视图,可以显示文章的注释。 每个注释都有一个按钮,单击该按钮时,如果登录的人是注释的所有者或管理员,则会删除该注释 我需要一种在ListView中以某种方式存储注释ID的方法,然后我需要检查注释作者的ID是否与登录用户的ID(存储在会话中)相同,如果匹配,则在单击时显示删除注释的按钮 请提供帮助。在ListView的ItemDataBound事件中,您可以获得绑定到ListView的数据项。此对象将具有您所需的所有ID 要处理click事件,需要ItemCommand事件。项目的ID

我有一个列表视图,可以显示文章的注释。 每个注释都有一个按钮,单击该按钮时,如果登录的人是注释的所有者或管理员,则会删除该注释

我需要一种在ListView中以某种方式存储注释ID的方法,然后我需要检查注释作者的ID是否与登录用户的ID(存储在会话中)相同,如果匹配,则在单击时显示删除注释的按钮


请提供帮助。

在ListView的ItemDataBound事件中,您可以获得绑定到ListView的数据项。此对象将具有您所需的所有ID

要处理click事件,需要ItemCommand事件。项目的ID可以通过Delete按钮作为命令参数传递


希望有帮助。

在ListView标记上指定DataKeyNames属性,然后在button click事件中获取DataKey

<asp:ListView runat="server" ID="myListView" DataKeyNames="CommentId" ...
或者在第四个列表项中获取commentId

int commentId = (int)myListView.DataKyes[3]["CommentId"];
编辑,当您进一步提到您的需求时

您可以在ItemDataBound事件中访问要绑定到列表视图的当前项

只需在ListView标记上添加ItemDataBound事件属性,并在事件中执行逻辑

<asp:ListView onitemdatabound="myListView_ItemDataBound" runat="server" ID="myListView" ...

protected void myListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        ListViewDataItem dataItem = (ListViewDataItem)e.Item;
        int commentId = (int)DataBinder.Eval(dataItem, "CommentId");

        // get author id based on comment id

        // or if you have auther id within the datasource
        // by which you are binding the listview then

        int ID_Author = (int)DataBinder.Eval(dataItem, "ID_Author");

        // get a reference to the delete button in the item
        // for instance you may do by this
        Control delete_button = e.Item.FindControl("deleteButtonId");

        // will hide if the author id don't match with the session id
        delete_button.Visible = ID_Author.Equals((int)Session["loggedin_userId"]);
    }
}

谢谢,这将从当前行中提取注释的id。现在我需要检查注释的attribue ID_Author是否等于登录用户的ID(存储在会话中),然后显示按钮。有什么想法吗?@barjed,您可以在ListView的ItemDataBound事件中执行这种类型的逻辑;当我为您添加示例代码时,我认为它应该是Eval语句中的dataItem.dataItem。至少对我来说是这样的。
<asp:ListView onitemdatabound="myListView_ItemDataBound" runat="server" ID="myListView" ...

protected void myListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        ListViewDataItem dataItem = (ListViewDataItem)e.Item;
        int commentId = (int)DataBinder.Eval(dataItem, "CommentId");

        // get author id based on comment id

        // or if you have auther id within the datasource
        // by which you are binding the listview then

        int ID_Author = (int)DataBinder.Eval(dataItem, "ID_Author");

        // get a reference to the delete button in the item
        // for instance you may do by this
        Control delete_button = e.Item.FindControl("deleteButtonId");

        // will hide if the author id don't match with the session id
        delete_button.Visible = ID_Author.Equals((int)Session["loggedin_userId"]);
    }
}