如何删除ListView中的项目?

时间:2013-03-07 09:37:30

标签: c# asp.net listview listviewitem

我想在我的asp.net ListView中删除一个条目,它不能用于我的代码。

我的代码:

protected void ListView_ItemCommand(object sender, ListViewCommandEventArgs e)
        {

            if (e.CommandName == "Delete")
            {
                int index = Convert.ToInt32(e.CommandArgument);

                int listcount = ListView.Items.Count;

                if (listcount - 1 == index)
                {
                    ListView.Items.RemoveAt(index); //go do ListView_Deleting 
                }

            }

        }

        protected void ListView_SelectedIndexChanging(object sender, EventArgs e)
        {
            //
        }

        protected void ListView_Deleting(object sender, EventArgs e)
        {
            //
        }

我的aspx:

 <div class="InputControlBox">
            <asp:ListView ID="ListView" runat="server" OnItemCommand="ListView_ItemCommand"
            OnSelectedIndexChanging="ListView_SelectedIndexChanging" OnItemDeleting="ListView_Deleting">
                <LayoutTemplate>
                    ...
                </LayoutTemplate>
                <ItemTemplate>
                  ...
                </ItemTemplate>
            </asp:ListView>
        </div>

错误在哪里?

1 个答案:

答案 0 :(得分:6)

你可以使用代码

if (e.CommandName == "Delete")
        {
            int index = Convert.ToInt32(e.CommandArgument);

            int listcount = ListView.Items.Count;

            if (listcount - 1 == index)
            {
                dataTable.Rows[index].Delete();

                ListView.datasource = datatable;
                ListView.DataBind();
            }

        }

其中dataTable是绑定到ListView的数据源。