简体   繁体   English

将项目插入下拉菜单时出现问题

[英]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. 我正在尝试在位置0插入新项目,但是在加载控件时,看不到新列表项或任何错误。

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. 由于DropDownList是绑定的,因此它将在DataTable中呈现“填充”。 You'll want to add the option for "Select Abstract ..." as a DataRow in the DataTable. 您需要将“选择摘要...”的选项添加为DataTable中的DataRow。 When you change the source of the .DataSource, it will reflect in the DropDownList. 当您更改.DataSource的源时,它将反映在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: 部分归功于HardCode,答案如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM