ListView:单击按钮时由其所有者删除行

时间:2011-02-20 16:41:42

标签: c# asp.net listview

我有一个ListView,显示文章的评论。 每个评论都有一个按钮,当单击该按钮时,如果记录的人是评论的所有者或管理员,则删除该评论。

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

请帮忙。

2 个答案:

答案 0 :(得分:1)

在ListView的ItemDataBound事件中,您可以获取绑定到ListView的数据项。该对象将包含您需要的所有ID。

要处理click事件,您需要ItemCommand事件。可以通过“删除”按钮将文章的ID作为命令参数传递。

希望它有所帮助。

答案 1 :(得分:1)

在ListView标记上指定DataKeyNames属性,然后在按钮单击事件中获取DataKey

<asp:ListView runat="server" ID="myListView" DataKeyNames="CommentId" ...

并在按钮点击事件中,您可以获取ID

(int)myListView.DataKeys[itemIndex]["CommentId"]

或在第四个ListItem中获取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"]);
    }
}