我有一个下拉列表,如下所示:
<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>
我需要能够从数据库中获取日期并尝试从下拉列表中自动选择正确的日期。
我的代码背后如下:
dim strDate as string = "10/31/2013"
DropDownList1.selectedvalue.contains(strDate)
类似的东西,但它没有从下拉列表中选择正确的值。
答案 0 :(得分:1)
其中任何一个都应该有用。我将遍历下拉项集合,然后将值拆分为数组。验证值实际包含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