Private MyObjectList As List (of SomeObject)
我在用户点击按钮的同时加载数据,将产品添加到购物篮并绑定数据列表。
Form_load....
dl.Datasource = MyObjectList
dl.databind()
End Sub
要在datalist中显示数据,我有一个标签,显示他们添加的内容,使用e eventArg将其转换为我的对象,例如:
Protected Sub dl_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.DataListItemEventArgs) Handles dl.ItemDataBound
Dim myObject = DirectCast(e.Item.DataItem, SomeObject)
....
Label.Text = myObject.Description
End Sub
内联代码是:
<asp:DataList ID="dl" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="DeletePRoduct" runat="server" Text="Delete" CommandName="Del" CommandArgument='<%# Container.ItemIndex %>'/>
</ItemTemplate>
</asp:DataList>
所以现在我希望用户能够删除产品
Protected Sub dl_ItemCommand(source As Object, e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles dl.ItemCommand
Dim myObject = DirectCast(e.Item.DataItem, SomeObject)
If e.CommandName = "Del" Then
MyObjectList.Remove(myObject)
....
End If
End Sub
如果我尝试在ItemCommand下传入myObject,我意识到我投入的e.item.DataItem是Nothing,因此它不会删除任何产品。然后我想通过行索引删除该产品,并在我意识到我无法执行此操作时向该按钮添加了一个CommandArgument,因为List需要一种SomeObject类型。
有人可以建议如何以这种方式删除对象吗?
由于
答案 0 :(得分:1)
从数据源DataList
中删除对象后,您必须再次绑定MyObjectList
以获取页面上的更新记录。
If e.CommandName = "Del" Then
MyObjectList.Remove(myObject)
dl.Datasource = MyObjectList
dl.databind()
....
End If
答案 1 :(得分:1)
您可以使用dl.DataKeys[e.Item.ItemIndex]
找到删除项目的ID。请务必设置DataKeyField
DataList
控件的<asp:DataList ID="dl" runat="server" DataKeyField="ID"...>
....
</asp:DataList>
Public Class SomeObject
Public Property ID() As Integer
Get
Return m_ID
End Get
Set
m_ID = Value
End Set
End Property
Private m_ID As Integer
Public Property Name() As String
Get
Return m_Name
End Get
Set
m_Name = Value
End Set
End Property
Private m_Name As String
End Class
Private _someObjects As List(Of SomeObject)
Public Property SomeObjects() As List(Of SomeObject)
Get
If _someObjects Is Nothing Then
_someObjects = New List(Of SomeObject)() With { _
New SomeObject() With { _
.ID = 1, _
.Name = "One" _
}, _
New SomeObject() With { _
.ID = 2, _
.Name = "Two" _
}, _
New SomeObject() With { _
.ID = 2, _
.Name = "Three" _
} _
}
End If
Return _someObjects
End Get
Set
SomeObjects = value
End Set
End Property
Protected Sub Page_Load(sender As Object, e As System.EventArgs)
If Not IsPostBack Then
dl.DataSource = SomeObjects
dl.DataBind()
End If
End Sub
Protected Sub dl_ItemCommand(source As Object, e As DataListCommandEventArgs)
If e.CommandName = "Del" Then
Dim id = Convert.ToInt32(dl.DataKeys(e.Item.ItemIndex))
Dim someObject = SomeObjects.First(Function(x) x.ID = id)
SomeObjects.Remove(someObject)
dl.DataSource = SomeObjects
dl.DataBind()
End If
End Sub
。
{{1}}
注意:删除后需要注意数据的持久性。例如,在ViewState,Session或Database中存储数据。