Home > Net >  ComboBox.SelectedValue.ToString() throw NullReferenceException
ComboBox.SelectedValue.ToString() throw NullReferenceException

Time:04-24

in my VS 2022 Community Edition, WindowsForms Project: I have a combobox with a SelectedValueChange Event and still getting an error:

System.NullReferenceException: Object not set to an instance of an object.

The code:

private void cmbChooseTask_SelectedValueChanged(object sender, EventArgs e)
{
    if (cmbChooseTask.SelectedValue.ToString() == "Install non clusterd instance")
    {
        Form frm = new NonClusterdInstallation();
        frm.Show();
    }

}

The combobox initialization is:

            cmbChooseTask.DataSource = new BindingSource(Dictionaries.DictTypeOfTask, null);
        cmbChooseTask.DisplayMember = "Value";
        cmbChooseTask.ValueMember = "Value";
        cmbChooseTask.SelectedItem = null;

and dictionary definition is:

        public static SortedDictionary<int, string> DictTypeOfTask = new SortedDictionary<int, string>()
    {
        { 1,"Install non clusterd instance" },
        { 2,"Install clusterd instance"},
        { 3, "Set up pre-installed cluster instance" },
        { 4, "Migration" },
        { 5, "Change Collation" },
        { 6, "Add instance to cluster" },
        { 7, "Display all" }
    };

CodePudding user response:

Quick solution to NRE would be:

if (String.Equals(cmbChooseTask.SelectedValue?.ToString(), "Install non 
clusterd instance"))

or just

if (cmbChooseTask.SelectedValue?.ToString() == "Install non 
clusterd instance")

CodePudding user response:

Why call ToString if it's already a string? Just cast it as type string, which will succeed for null too:

if ((string)cmbChooseTask.SelectedValue == "Install non clusterd instance")

Also, based on the text you're comparing it to, I'm guessing that you actually care about the text displayed in the control, which is exposed via the Text property, which is already type string:

if (cmbChooseTask.Text == "Install non clusterd instance")
  • Related