2009-06-08 38 views
0

我繼承了DropDownList以添加兩個自定義ListItems。第一個項目是「選擇一個...」,第二個項目在最後添加,它的值是「自定義」。繼承DropDownList並使用其DataSourceObject添加自定義值

我重寫的DataBind和使用下面的代碼:

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() 

的問題是,如果數據源是以外的任何其他列表項的列表這個代碼將無法正常工作。有沒有更好的方法來做到這一點?

回答

0

你可以做這樣的假設數據源總是繼承IList的,在這種情況下,你可以做到以下幾點:

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

當然,這是假定任何數據源,它允許你添加ListItem類型的對象。但是這可能足以滿足您的需求。

0

您可以單獨放置數據綁定並在DataBound事件處理程序中添加特殊項目。

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 

(我的VB.NET是有限的,所以你可能需要調整語法)