0

I am working on a listbox but I need some buttons to be enabled depending on the selectedItem, so I coded this:

        private void lstLSD_SelectedIndexChanged(object sender, EventArgs e)
    {
        registroSeleccionado = (Registro)this.lstLSD.SelectedItem;
        label2.Text = "Registro " + registroSeleccionado;
        string item = lstLSD.SelectedItem.ToString();
        if (item.StartsWith("01")) { button1.Enabled = true; } else { button1.Enabled = false; };
        if (item.StartsWith("02")) { button3.Enabled = true; } else { button3.Enabled = false; };
        if (item.StartsWith("03")) { button4.Enabled = true; } else { button4.Enabled = false; };
        if (item.StartsWith("04")) { button5.Enabled = true; } else { button5.Enabled = false; };
    }

But, I am loosing the ability to modify that same selectedItem later..

        private void btnCrear_Click(object sender, EventArgs e)
    {
        if (txtR1Modificado.TextLength >0)
        {
            Registro modifReg = new Registro()
            {
                Registro1 = txtR1Modificado.Text
            };

            int index = Form1.formInicialInstance.lstB.SelectedIndex;

            Form1.formInicialInstance.lstB.Items.RemoveAt(index);
            Form1.formInicialInstance.lstB.Items.Insert(index, modifReg);
            Form1.formInicialInstance.lstB.SetSelected(index, true);
            txtR1Modificado.Clear();
        }


    }

And this is the error I am getting: System.NullReferenceException: 'Referencia a objeto no establecida como instancia de un objeto.'

System.Windows.Forms.ListBox.SelectedItem.get devolvió null.

Any Idea? Thanks for your help!

Alejandro
  • 23
  • 3
  • Welcome to Stack Overflow! Does [what is a nullreferenceexception and how do I fix it](https://stackoverflow.com/q/4660142/16563198) help? It looks like the line `int index = Form1.formInicialInstance.lstB.SelectedIndex;` may be the one throwing the exception, however as you haven't included the definitions of `formInicialInstance` and `lstB` and how they are set / instantiated, it's impossible to answer the question in its current form. Please edit the question to include that information. – sbridewell Apr 27 '22 at 16:36

1 Answers1

0

It's possible that there is no current selection, in which case you'd get null back from SelectedItem.

You need to check for SelectedIndex not being -1:

private void lstLSD_SelectedIndexChanged(object sender, EventArgs e)
{
    if (this.lstLSD.SelectedIndex != -1) {
        registroSeleccionado = (Registro)this.lstLSD.SelectedItem;
        label2.Text = "Registro " + registroSeleccionado;
        string item = lstLSD.SelectedItem.ToString();
        button1.Enabled = item.StartsWith("01");
        button3.Enabled = item.StartsWith("02");
        button4.Enabled = item.StartsWith("03");
        button5.Enabled = item.StartsWith("04");
    }
}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40