如何向Dropdownlist添加新值

时间:2013-11-08 16:09:06

标签: asp.net

我正在将数据源加载到下拉列表和绑定,但在某些情况下新值即将发生(区分大小写),因此我无法将下拉列表设置为选定值? 如何实现这一点,意味着在下拉列表中将datagrid选中的值显示为文本?

将数据填充到下拉列表中

Me.RmtRouterName.DataSource = Me.datareader_1param("pr_list_dev_by_site", 
    SiteID, "@enter_value")
Me.RmtRouterName.DataTextField = "devname"
Me.RmtRouterName.DataValueField = "devname"

从datagrid读取值

tmpstr = MyIIF(Me.SiteInfo1.Tables(SiteInfoTableName).Rows(0), "RmtRouterName")
If (tmpstr = String.Empty) Then
   Me.RmtRouterName.SelectedIndex = -1
Else
   Me.RmtRouterName.SelectedValue = tmpstr

在某些情况下,datareader值和datgrid值不匹配(由于区分大小写)如何克服此问题

1 个答案:

答案 0 :(得分:0)

Else逻辑中,在尝试设置SelectedValue之前尝试在下拉列表中查找文本值,如下所示:

助手功能:

Public Function FindByTextCaseInsensitive(ByVal ctl As ListControl, ByVal text As String) As ListItem
    If ctl Is Nothing Then 
        Return Nothing
    End If

    For Each li As ListItem In ctl.Items
        If String.Compare(li.Text, text, True) = 0 Then 
            Return li
        End If
    Next

    Return Nothing
End Function

现在在Else区块中,执行以下操作:

Else
    Dim foundItem As ListItem = FindByTextCaseInsensitive(tmpstr)

    If foundItem Is Nothing Then
        Me.RmtRouterName.SelectedIndex = -1
    Else
        Me.RmtRouterName.SelectedValue = tmpstr
    End If
End If