Search code examples
vb.netvisual-studiogoogle-apigoogle-translation-api

Google Translate API conversion


Would anyone be able to help me with my translator using the google translate API? It comes up with an error on the very last line System.InvalidCastException: 'Conversion from type 'TranslationResult' to type 'String' is not valid.' This is the code here

    Private Sub TranslateText(InputText)
        Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "C:\Users\student\Desktop\sunlit-runway-279702-175183ddeace.json")
        Dim Client = TranslationClient.Create()
        Dim InText = InputText.text
        Dim response = Client.TranslateText(InText, LanguageCodes.Japanese, LanguageCodes.English)
        Output.Text(response.TranslatedText)
    End Sub

When I use a message box it works however I want it to be displayed in a textbox


Solution

  • Text is a property of textbox, not a function. To set the text of a textbox it's like this:

    myTextBox.Text = "Hello word"
    

    Not like this

    myTextbox.Text("Hello world")
    

    This is different to mesagebox.show which IS a function and DOES take a string parameter

    MessageBox.Show("Hello World")
    

    So, to set the textbox text to the translated result:

    myTextbox.Text =  response.TranslatedText 'translated text is a string, like "Hello World"
    

    Really I think your code should look like:

    Private Function TranslateJapanese(inputText as string) as string
        Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "C:\Users\student\Desktop\sunlit-runway-279702-175183ddeace.json")
        Dim Client = TranslationClient.Create()
        Dim response = Client.TranslateText(inputText, LanguageCodes.Japanese, LanguageCodes.English)
        Return response.TranslatedText
    End Sub
    

    And be used like:

    englishTextbox.Text = TranslateJapanese(japaneseTextbox.Text)