It appears that VB in VS8 doesn't support/convert lambda expressions with a statement body. I'm using them in my C# application, but now must convert it to VB.
I'm creating a whole bunch of controls dynamically, and I want to be able to give them event handlers on the fly. This is so I can build a dynamic user interface from a database. In the following code I'll create a form and a checkbox, make the checkbox control the form's visibility, add a few method handlers to the form, and then add the newly created checkbox to a pre-existing form/panel/etc. Handlers for the form, for instance, affect the checkbox:
// Inside some loop creating a lot of these forms and matching checkboxes
Form frmTemp = frmTestPanels[i]; // New form in array
CheckBox chkSelectPanel; // New checkbox that selects this panel
chkSelectPanel = new CheckBox();
chkSelectPanel.Text = SomeName; // Give checkbox a label
chkSelectPanel.Click += (ss, ee) => // When clicked
{
label1.Text = SomeName; // Update a label
if (chkSelectPanel.Checked) // Show or hide the form
{
frmTemp.Show();
}
else
{
frmTemp.Hide();
}
};
frmTemp.VisibleChanged += (ss, ee) => // When form visibility changes
{
chkSelectPanel.Checked = frmTemp.Visible; // Reflect change to checkbox
ConfigurationFileChanged = true; // Update config file later
};
frmTemp.FormClosing += (ss, ee) => // When the form closes
{ // We're only pretending to close the form - it'll sit around until needed
chkSelectPanel.Checked = false; // Update the checkbox
frmTemp.Hide(); // Hide the form
ee.Cancel = true; // Cancel the close
};
flpSelectGroup.Controls.Add(chkSelectPanel); // Add checkbox to flow layout panel
// End of loop creating a bunch of these matching forms/checkboxes
Of course, I'm getting the conversion error, "VB does not support anonymous methods/lambda expressions with a statement body"
I really liked the ability to create everything on the fly, and then let the objects handle themselves - I don't need to add any special functions that figure out which form is giving the close event so it can search for the right checkbox and update the checkbox - It Just Works (TM).
Unfortunately it needs to be converted to VB.
- What is the best way to convert lambda/anonymous statement bodies into something that will work in VB, especially when one needs to create many of them?
-Adam
Could you make a new class that accepts the
Form
in the constructor and haschkSelectPanel
as a field, allowing you to use instance methods as your event handlers?Wait for the nearest release of .NET 4, it will support things like this in VB. Don't see other alternative.
Ugly alternatives are:
This work, but you can use a single statement in a function.
Create some regular Sub Foo
and use
AddHandler
to bind it to an event