ilivewithian
ilivewithian

Reputation: 19712

Struggling with VB .net Lambdas

I'm trying to use lambdas in some VB.Net code, essentially I'm trying to set a flag when databound is called.

Simplified it looks like this:

Dim dropdownlist As New DropDownList()
dropdownlist.DataSource = New String() {"one", "two"}
Dim databoundCalled As Boolean = False
AddHandler dropdownlist.DataBound, Function(o, e) (databoundCalled = True)
dropdownlist.DataBind()

My understanding is that the databoundCalled variable should be set to true, clearly I'm missing something as the variable always remains false.

What do I need to do to fix it?

Upvotes: 5

Views: 758

Answers (3)

almog.ori
almog.ori

Reputation: 7889

Single line Lambdas in vb.net ALWAYS are expressions , what your lambda expression is doing is basically saying does databoundCalled = True or (databoundCalled == True) if your a c# guy , not set databoundCalled = True

Upvotes: 3

JaredPar
JaredPar

Reputation: 755587

The problem is how lambdas are interpreted. In VS2008 a Function lambda is always interpreted as an expression and not a statement. Take the following block of code as an example

Dim x = 42
Dim del = Function() x = 32
del()

In this case, the code inside the lambda del is not doing an assignment. It is instead doing a comparison between the variable x and the value 32. The reason why is that VB has no concept of an expression that is an assignment, only a statement can be an assignment in VB.

In order to do an assignment in a lambda expression you must have statement capabilities. This won't be available until VS2010 but when it is you can do the following

Dim del = Function()
           x = 32
          End Function

Essentially anything that is not a single line lambda is interpreted as a statement.

Upvotes: 1

CodeLikeBeaker
CodeLikeBeaker

Reputation: 21312

After looking over your code and scratching my head, I found a solution that works. Now, why this works over what you have, I am not clear. Maybe this will at least help you in the right direction. The key difference is I have a method that sets the value to true/false. Everything else is the same.

Here is my entire web project code:

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Dim databoundCalled As Boolean = False
    Dim dropdownlist As New DropDownList()

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Response.Write(databoundCalled)
        Bind()
        Response.Write(databoundCalled)

    End Sub

    Sub Bind()
        AddHandler dropdownlist.DataBound, Function(o, e) (SetValue(True))

        dropdownlist.DataSource = New String() {"one", "two"}
        dropdownlist.DataBind()
    End Sub

    Function SetValue(ByVal value As Boolean) As Boolean
        databoundCalled = value
        Return value
    End Function
End Class

I hope this helps!

Upvotes: 7

Related Questions