开发者

Problem inserting item into drop down

Seems to be a trivial problem, but can't pinpoint a solution.

I have a drop down bound to a datatable. I'm trying to insert a new item at position 0, but when the control is loaded, I don't see the new listitem or any errors.

Public Sub Page_Load(ByVal sender As Object, ByVal e As eventargs) Handles Me.Load
    If Not Page.IsPostBack Then
        loadRegistrantAbstracts()
    End If
End Sub
Public Sub loadRegistrantAbstracts()
    Dim obj As New Lookups
   开发者_开发知识库 Dim dtAbstracts As DataTable

    dtAbstracts = obj.getAbstracts()

    If dtAbstracts.Rows.Count > 0 Then
        With ddlAbstracts
            .DataSource = dtAbstracts
            .DataTextField = "DisplayName"
            .DataValueField = "AbstractID"
            .DataBind()
            .Items.Insert(0, New ListItem("Select Abstract..", "0"))
        End With
    End If
End Sub


Since the DropDownList is bound, it will render the "stuff" in the DataTable. You'll want to add the option for "Select Abstract ..." as a DataRow in the DataTable. When you change the source of the .DataSource, it will reflect in the DropDownList.

Most likely you are loading this from a database, so you may decide to include the "Select ..." option in the query:

SELECT 0 AS id, 'Select Abstract ...' AS abstract_name, 0 AS sort_order
UNION
SELECT dbo.abstracts.id, dbo.abstracts.name AS abstract_name, 1 as sort_order FROM dbo.abstracts
ORDER BY sort_order, abstract_name


The answer, thanks in part to HardCode, was the following:

Public Sub Page_Load(ByVal sender As Object, ByVal e As eventargs) Handles Me.Load
    If Not Page.IsPostBack Then
        loadRegistrantAbstracts()
    End If
End Sub
Public Sub loadRegistrantAbstracts()
    Dim obj As New Lookups
    Dim dtAbstracts As DataTable

    dtAbstracts = obj.getAbstracts()

    Dim row As DataRow = dtAbstracts.NewRow

    row("DisplayName") = "Select Abstract..."
    row("AbstractID") = "0"

    dtAbstracts.Rows.InsertAt(row, 0)

    If dtAbstracts.Rows.Count > 0 Then
        With ddlAbstracts
            .DataSource = dtAbstracts
            .DataTextField = "DisplayName"
            .DataValueField = "AbstractID"
            .DataBind()
        End With
    End If
End Sub
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜