在 vb.net 的下拉列表中查找值是否包含字符串

Find if value contains a string in a drop down list in vb.net

我有一个如下所示的下拉列表:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
                        <asp:ListItem Text="Text1" Value="6,08/04/2015,P"></asp:ListItem>
                        <asp:ListItem Text="Text2" Value="5,11/17/2014,S"></asp:ListItem>
                        <asp:ListItem Text="Text3" Value="4,05/26/2014,P"></asp:ListItem>
                        <asp:ListItem Text="Text4" Value="3,01/20/2014,A"></asp:ListItem>
                        <asp:ListItem Text="Text5" Value="2,10/31/2013,G"></asp:ListItem>
                        <asp:ListItem Text="Text6" Value="1,04/09/2013,P"></asp:ListItem>
</asp:DropDownList>

我需要能够从数据库中获取日期并尝试从下拉列表中自动 select 正确的日期。

我后面的代码如下:

dim strDate as string = "10/31/2013"

DropDownList1.selectedvalue.contains(strDate)

类似的东西,但它 select 不是下拉列表中的正确值。

这些都应该有效。我会遍历下拉项集合,然后将值拆分为一个数组。验证这些值实际上包含 3 个值并获取第二个值以与 strDate 进行比较。验证值匹配后,将项目设置为通过以下任一方法选择并退出 For Each 循环,以防存在重复项,它将获取第一个。

Dim strDate As String = "10/31/2013"

For Each item As ListItem In DropDownList1.Items

    Dim split As Array = item.Value.ToString.Split(",")

    'verify the value is split to 3 values
    If split.GetUpperBound(0) = 2 Then

        'get 2nd item which is 1 as array are 0 based
        If split(1) = strDate Then
            item.Attributes.Add("selected", "true")
            Exit For
        End If

    End If

Next

'OR

For Each item As ListItem In DropDownList1.Items

    Dim split As Array = item.Value.ToString.Split(",")

    'verify the value is split to 3 values
    If split.GetUpperBound(0) = 2 Then

        'get 2nd item which is 1 as array are 0 based
        If split(1) = strDate Then
            DropDownList1.SelectedValue = item.Value
            Exit For
        End If

    End If

Next