I want to get the chosen language from the Form1 combobox and enable other forms to view the language. The combobox has approximately 20 languages, so yes quite a few you could say! I have a method called ComboBoxLang_SelectedIndexChanged (occurs when the language in the combobox is changed):
// Works fine in Form1.cs
private void ComboBoxLang_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedItem = this.comboBoxLang.GetItemText(this.comboBoxLang.SelectedItem);
comboBox2.Items.Clear();
if (selectedItem == "English")
{
ToEnglish();
}
else if (selectedItem == "French")
{
ToFrench();
}
// And so on...
}
For the moment, to test that it works I just want to display a message of the language chosen in another form. I have researched and have tried multiple ways, but obviously I am going wrong somewhere! I thought may be using the get and set method would be most useful but I'm really not sure. I want the MessageBox to say "English" or whatever the selection is.
Another example, I know that using
Form1 f1 = new Form1();
... in the second form that is trying to retrieve the value is incorrect as it just gets the hard-coded text and I just want the actual value that has been entered. So I wasn't sure if I should use
private Form1 f1;
... in the second form instead. I am really confused.
I know this is a common question but I can't seem to find a solution.
an easy way would be to make a public class and store combobox value in its string variable. and then (within other form) take that string value from that class
Lets do it via observer
With this, all forms can subscribe to the event
LanguageChanged
and the formForm1
can "notify" - all other forms will get the infoEdit
The observer pattern is when you have classes that "observe" changes in other classes. In .net observer is implemented using Events and Delegates. Sounds scary but in reality it makes it simple. You subscribe to class event and observe the change you want to observe. In this case, when language is changed in the Form1, you should call
LanguageChangeObserver.Notify(...)
. The other forms, when created, should subscribe toLanguageChanged
event.If the form is closed and about to be disposed, you should unsubscribe from the observing because wired and not un-wired handlers is common method of memory leaks in .Net
Lock
will synchronize your code and make sure, you change one language at the time. I hope this helps.I have managed to create a solution! See the link for my answer but in another related question of mine with an explanation and code:
https://stackoverflow.com/a/21310270/2952390
SO simple!