Question

Im trying to fill combobox from one of two arraylist, on changing selection in listview with method listView1_SelectedIndexChanged. The problem is it works fine the first time, but the second time I get the following error: "Object reference not set to an instance of an object."

The error is probably happening here: string pr = listView1.FocusedItem.Text;

Please help.

    private void listView1_SelectedIndexChanged(object sender, EventArgs e)
    {

        ArrayList Profesor1 = new ArrayList();
        Profesor1.Add("Kolegij 1 profesor 1");
        Profesor1.Add("Kolegij 2 profesor 1");



        ArrayList Profesor2 = new ArrayList();
        Profesor2.Add("Kolegij 1 profesor 2");
        Profesor2.Add("Kolegij 2 profesor 2");



        string pr = listView1.FocusedItem.Text; //posible prob
        switch (pr)
        {
            case "Profesor 1": comboBox1.DataSource = Profesor1;
                break;
            case "Profesor 2": comboBox1.DataSource = Profesor2;
                break;
        }
    }
Was it helpful?

Solution

Is there something else going on in your example affecting the listView1 item? I've mocked up a small clone of your question and I can't seem to replicate the error:

I'm using your code for the event handler, and I'm populating the listView1 thusly:

        listView1.Items.Add("Profesor 1");
        listView1.Items.Add("Profesor 2");

It sounds like you're causing the listView1_SelectedIndexChanged handler to be fired in the background.

As a slight aside, your array lists aren't going to change, you probably don't want to keep your ArrayList creation in your event handler and keep recreating them each time (they don't seem to have any dynamic information in). particularly as that handler will often be called twice once, for the deselection, and again for a selection.

On that last point, it's also worth having a look at the ItemSelectionChanged event, which could be used to help your initial problem, as it comes with ListViewItemSelectionChangedEventArgs which contain the property IsSelected, which you could use to verify that you have an object selected.

e.g:

private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
    {
        if (e.IsSelected)
        {
            // Your code here.
            // e.Item...
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top