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

I have a dropdown that looks like this:

<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> 

I need to be able to get the date from the database and try to automatically select the correct date from the drop-down list.

my code is as follows:

 dim strDate as string = "10/31/2013" DropDownList1.selectedvalue.contains(strDate) 

something like this, but it does not select the correct value from the drop-down list.

0
drop-down-menu
source share
1 answer

Any of these should work. I would scroll through the collection of dropdowns and then split the value into an array. Confirm that the values โ€‹โ€‹actually contain 3 values โ€‹โ€‹and get the second for comparison with strDate. After you check the coincidence of values, set the element as selected by one of the methods described below and exit the "For Each" cycle, if there are duplicates, it will capture the first one.

 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 
+1
source share

All Articles