I have a form named "form1" in vb.net. This form has many controls. I opened the form1.designer.vb file and put in an if else expression such as:
If getLanguage() = "en" then label1.text = "Good Morning" Else label1.Text = "Bonjour"
This works perfectly fine in runtime.
If I open the Form1.vb [Design] page in design, and make any changes, the code above disappears.
Is there a way I can keep any code I put in the designer page? I don't want to put them in the load event in the form1.vb file.
Locate this code :
Public Sub New()
Me.InitializeComponent()
End Sub
Then add a line :
Public Sub New()
Me.InitializeComponent()
Me.MakeComponentsChanges()
End Sub
Then create the method in form1.vb or another Partial Class copy of your creation :
Private Sub MakeComponentsChanges()
If getLanguage() = "en" then
label1.text = "Good Morning"
Else
label1.Text = "Bonjour"
End If
End Sub
Don't touch the form1.designer.vb (.cs)
And as stated in other answers, better use .Localizable
Property in the IDE and change it from False
to True
. Then you'll gain access to several default languages. You don't have to bother writing code.
English
for example.French
.Form1.en.resx
and Form1.fr.resx
(or so) along with Form1.vb
and Form1.Designer.vb
. Don't edit them !If you open the en.resx or fr.resx, you'll see that the edits you've made are in there. Those files are used to store inbuilt Lang-related ressources for your form. That's flatly called Globalization.
Then locate again the constructor of your Form.
Public Sub New()
Me.InitializeComponent()
'Me.MakeComponentsChanges()
' Now you know about some Globalization,
' you may get rid of that Method.
' Add two variables :
Dim OriginalCulture As CultureInfo
Dim CurrentOSCulture As CultureInfo
' Initialize them
OriginalCulture = Thread.CurrentThread.CurrentCulture
CurrentOSCulture = CultureInfo.CurrentCulture
' Do this test :
Try
Thread.CurrentThread.CurrentCulture = CurrentOSCulture ' may fail
Thread.CurrentThread.CurrentUICulture = CurrentOSCulture ' may fail
' Attempt to match the current Thread culture to the Operating System one.
Catch CurrentException As Exception
Thread.CurrentThread.CurrentCulture = OriginalCulture
Thread.CurrentThread.CurrentUICulture = OriginalCulture
' If it fails, revert back to default as defined in your IDE
End Try
End Sub
Don't forget to add on top of your Class declaration those two namespaces :
Imports System.Globalization
Imports System.Threading
And voilà ! I know I said you don't have to bother writing code, but the bits above in the constructor are enough to handle the selection of a language. Plus besoin de taper du code superflu après ça.