EUREKA!!
我高兴得超乎想象!!全部大写,也不加粗,都无法体现我现在有多高兴:)
首先我想给道具这个问题 https://stackoverflow.com/questions/825048/accessing-controls-in-the-edititemtemplate-of-a-listview这让我指明了正确的方向。现在来看答案,这是我发现的上述链接中提供的答案的最理想的变体:
The ItemDataBound
事件是关键,但重要的是要注意,此事件将为您中存在的每个项目触发ListView
因此,你必须小心行事。这里有两个对我同样有效的选择。
Option 1- 最优雅;仅对有问题的项目而不是所有项目运行 FindControl。
Protected Sub NewProduct_ItemDataBound(ByVal sender As ListView, ByVal e As ListViewItemEventArgs) Handles NewProduct.ItemDataBound
Dim i As Integer = sender.EditIndex
If i = e.Item.DataItemIndex Then
Dim ddl As DropDownList = DirectCast(e.Item.FindControl("NewProductName_ddl"), DropDownList)
Dim tb As TextBox = DirectCast(e.Item.FindControl("NewProductName_cb"), TextBox)
ddl.Items.FindByValue(sender.DataKeys(i)("ID").ToString).Selected = True 'Prefills the DropDownList
tb.Text = sender.DataKeys(i)("Product").ToString 'Prefills the TextBox
End If
End Sub
Option 2- 基于引用的问题,但进行了关键检查以确保非空对象。
Protected Sub NewProduct_ItemDataBound(ByVal sender As ListView, ByVal e As ListViewItemEventArgs) Handles NewProduct.ItemDataBound
Dim i As Integer = sender.EditIndex
If i > -1 Then
Dim ddl As DropDownList = DirectCast(e.Item.FindControl("NewProductName_ddl"), DropDownList)
Dim tb As TextBox = DirectCast(e.Item.FindControl("NewProductName_cb"), TextBox)
If Not IsNothing(ddl) Then
ddl.Items.FindByValue(sender.DataKeys(i)("ID").ToString).Selected = True 'Prefills the DropDownList
End If
If Not IsNothing(tb) Then
tb.Text = sender.DataKeys(i)("Product").ToString 'Prefills the TextBox
End If
End If
End Sub
我稍后可能会改进这个答案,但这对我有用。 :)