views:

334

answers:

2

I'm inheriting a DropDownList to add two custom ListItems. The first item is "Select one..." and the second item gets added at the end, it's value is "Custom".

I override DataBind and use the following code:

    Dim data As List(Of ListItem) = CType(DataSource, List(Of ListItem))
    data.Insert(0, New ListItem("Select one...", SelectOneListItemValue))
    If DisplayCustomOption Then
        data.Insert(data.Count, New ListItem("Custom", CustomListItemValue))
    End If
    DataSource = data
    MyBase.DataBind()

The problem is this code won't work if the DataSource is anything other than a List of ListItem. Is there a better way of doing this?

A: 

You could make the assumption that the data source always inherits IList, in which case you could do the following:

Dim data As IList = CType(DataSource, IList)
data.Insert(0, New ListItem("Select one...", SelectOneListItemValue))
' And so on...

Of course, this assumes that whatever the data source is, it allows you to add objects of the type ListItem. But this might be generic enough for what you need.

Blixt
A: 

You could just leave the databind alone and add your special Items in the DataBound event handler.

Protected Sub MyDropDownList_DataBound(sender As Object, e As EventArgs) _ 
    Handles MyDropDownList.DataBound 

        MyBase.Items.Insert(0, New ListItem("Select One...", SelectOneListItemValue))

        If DisplayCustomOption Then
            MyBase.Add(New ListItem("Custom", Custom))
        End If
End Sub

(My VB.NET is limited, so you may need to adjust syntax)

HectorMac