Search code examples
asp.netvb.netlistviewlistviewitem

Add New Item to Already Bound ListView in ASP Net (Unable to set DataKeys/FieldName)


My overall goal is to add fake/unbound items to a listview control (for final HTML Table output reasons). This is a code behind solution. Users will not be adding items as it will be outputted in a rigid table.

I have looked at several examples and while this is easy for a dropdown it is not for listview.

The code below works without error, but my item is not shown on runtime. I think the class is not setting the item fieldname correctly, but I can't figure out the right syntax to fix it.

ColumnNameAList.DataSource = PeriodDataView
ColumnNameAList.DataBind()

Dim test As New Example1("ColumnNameA")

Dim newItem As New ListViewDataItem(ColumnNameAList.Items.Count, ColumnNameAList.Items.Count)
newItem.DataItem = test

ColumnNameAList.Items.Insert(ColumnNameAList.Items.Count, newItem)
ColumnNameAList.Items.Add(newItem)

Here is the Example1 class that is supposed to set the DataValueField:

Public Class Example1
Public Sub New(ColumnNameA__1 As String)
    ColumnNameA = ColumnNameA__1
End Sub

Private m_ColumnNameA As String

Public Property ColumnNameA() As String
    Get
        Return m_ColumnNameA
    End Get
    Set(value As String)
        m_ColumnNameA = value
    End Set
End Property

End Class

This outputs my original datasource list, but not the added item.

<ItemTemplate>
    <td>
        <%# Eval("ColumnNameA")%>

    </td>
</ItemTemplate>

Solution

  • In the end I could only reliably solve this with a codebehind solution. I made a copy of the original datasource, modified my copy and then databound to it.

    Dim MyOriginalTableSource As Data.DataView = DataManager.example()
    Dim ModifiedTable As DataTable = MyOriginalTableSource.ToTable
    'do stuff here
    Mylistbox.DataSource = ModifiedTable
    Mylistbox.DataBind()
    

    Won't work for everyone, but in this case it works fine for me.