I am trying to write extension methods in VB.NET
Imports System.Runtime.CompilerServices
Module ExtensionMethods
<Extension()> _
Public Function FindByText(ByVal collection As ListItemCollection, text As String, comparisonType As StringComparison) As ListItem
Dim result As ListItem = collection.OfType(Of ListItem)().FirstOrDefault(Function(s) s.Text.Equals(text, comparisonType))
Return result
End Function
<Extension()> _
Public Function FindByValue(ByVal collection As ListItemCollection, text As String, comparisonType As StringComparison) As ListItem
Dim result As ListItem = collection.OfType(Of ListItem)().FirstOrDefault(Function(s) s.Value.Equals(text, comparisonType))
Return result
End Function
End Module
But I am getting this error.
Class 'System.Web.UI.WebControls.ListItem' cannot be indexed because it has no default property
What could be wrong?
I am calling the code like this.
ddlSalesmanager.Items.FindByText(survey, StringComparison.CurrentCultureIgnoreCase)
PS: I ported this wonderful code from C# to VB
survey
?). collection.Cast(Of ListItem)()
instead of collection.OfType(Of ListItem)()
since all objects in a ListItemCollection
are of type ListItem
by nature. Tested with
<asp:DropDownList ID="DdlFoo" runat="server" AutoPostBack="true" OnSelectedIndexChanged="FooSelected" >
<asp:ListItem Text="Foo1" Value="1"></asp:ListItem>
<asp:ListItem Text="Foo2" Value="2"></asp:ListItem>
<asp:ListItem Text="Foo3" Value="3"></asp:ListItem>
</asp:DropDownList>
And in the SelectedIndexChanged
event-handler:
Dim foo2 = DirectCast(sender, DropDownList).Items.FindByText("FOO2", StringComparison.CurrentCultureIgnoreCase)
If Not foo2 Is Nothing Then
' your overloaded extension is called successfully
End If
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.