Home > Software engineering >  Translate C# to VB
Translate C# to VB

Time:09-13

I have method SwitchScreen to change userControl. I want change my app from C# to VB. I tried to find on google but no result. Can someone help? :(

here is my method:

 public void SwitchScreen(object sender, string getText)
    {
        var screen = (UserControl)sender;
        headerTitle.Text = getText;

        if ((screen) != null)
        {
            StackPanelMain.Children.Clear();
            StackPanelMain.Children.Add(screen);
        }
    }

i've tried like this in VB:

 Public Sub SwitchScreen(sender As Object, getText As String)

    Dim Screen = sender(UserControl)
    headerTitle.Text = getText

    If (Screen Is Nothing) Then
        StackPanelMain.Children.Clear()
        StackPanelMain.Children.Add(Screen)
    End If
End Sub

But error on Dim Screen = sender(UserControl), 'UserControl' is a class type and cannot be used as an expression.

CodePudding user response:

This should work

Public Sub SwitchScreen(sender As Object, getText As String)

    Dim Screen as UserControl = sender
    headerTitle.Text = getText

    If (Screen IsNot Nothing) Then
        StackPanelMain.Children.Clear()
        StackPanelMain.Children.Add(Screen)
    End If
End Sub

vb should auto cast - a cast probably not required.

CodePudding user response:

You're changing the meaning of that line when you write it that way.

C#

        var screen = (UserControl)sender;

This is taking the 'sender' var, casting as a 'UserControl' class, and setting to be referenced by the 'screen' var.

VB

    Dim Screen = sender(UserControl)

It's been a while since I worked in VB, but it looks like you're calling a function named 'Sender' and passing 'UserControl' as a parameter, which it is not.

you need to find the VB equivilent of 'cast as Object' for your sender var.

Maybe

Dim Screen = CType(sender, UserControl)

CodePudding user response:

Public Sub SwitchScreen(sender As Object, getText As String)

    Dim Screen As UserControl = TryCast(sender, UserControl)
    headerTitle.Text = getText

    If (Screen IsNot Nothing) Then
        StackPanelMain.Children.Clear()
        StackPanelMain.Children.Add(Screen)
    End If
End Sub
  • Related