Accessing ComboBox text/value in another Form

Total Post:183

Points:1285
C# 
C#
 1209  View(s)
Ratings:
Rate this:

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.

 I have a method called ComboBoxLang_SelectedIndexChanged (occurs when the language in the combobo 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 == Language.English)
    {
        ToEnglish();
    }
    else if (selectedItem == Language.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! For example:

internal string comboBoxVal
{
    get
    {
        return comboBoxLang.SelectedItem.ToString();
    }
}

But this comes up with an error: "NullReferenceException was unhandled, Object reference not set to an instance of an object".

  1. Post:412

    Points:2888
    Re: Accessing ComboBox text/value in another Form

    Hi Ankita,


    You can try this:
    public static class LanguageChangeObserver
    {
        public static object _lock = new object();
        public delegate void LanguageHandler(string lang);
        public static event LanguageHandler LanguageChanged;
        public static void  Notify(string lang)
        {
            lock (_lock)
            {
                if (LanguageChanged != null)
                    LanguageChanged(lang);
            }
        }
    }

    With this, all forms can subscribe to the event LanguageChanged and the form Form1 can "notify" - all other forms will get the info.

      Modified On Apr-03-2018 11:59:14 PM

Answer