ASP.NET ListView with identical markup in EditItemTemplate and InsertItemTemplate

耗尽温柔 提交于 2019-12-04 20:21:58

I've ended up making a custom ListView that makes this straightforward. If there is no InsertItemTemplate, then the EditItemTemplate is used for both:

    Private Sub ListView_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        If Me.InsertItemTemplate Is Nothing Then
            Me.InsertItemTemplate = Me.EditItemTemplate
        End If
    End Sub

I've also created a custom "save" button that switches its commandname between "Update" and "Insert" as appropriate:

    Private Sub SaveLinkButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
        Dim _ListView As Controls.ListView = GetListView()
        If _ListView IsNot Nothing Then
            If Me.BindingContainer Is _ListView.EditItem Then
                Me.CommandName = "Update"
            Else
                Me.CommandName = "Insert"
            End If
        End If
    End Sub

(The GetListView function above just walks up the button's parents until it finds a ListView.)

That's it - hope this is helpful to someone.

I'm very late to the party, but for anyone looking for a declarative solution, I ended up doing the following (control is my FormView):

if (control.EditItemTemplate == null)
{
    control.EditItemTemplate = control.InsertItemTemplate;
}

And for the template:

<InsertItemTemplate>

    ... template ...

    <asp:LinkButton Text="Insert" CommandName="Insert" runat="server" 
                    Visible='<%# Container.ItemType == ListViewItemType.InsertItem %>' />
    <asp:LinkButton Text="Update" CommandName="Update" runat="server"
                    Visible='<%# Container.ItemType == ListViewItemType.DataItem %>' />
    <asp:LinkButton Text="Cancel" CommandName="Cancel" runat="server" 
                    Visible='<%# Container.ItemType == ListViewItemType.DataItem %>' />
</InsertItemTemplate>

Where the interesting bit is obviously: Container.ItemType == ListViewItemType.DataItem (and others). This correctly sets the visibility of the buttons according to the template type.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!