简体   繁体   中英

c# - listview does not add items when using a delegate

Using a worker thread, I am adding items to a ListView, however to do this I have implemented a delegate in the form as shown below in the code sample.

Problem:

When the ListView.Items.add() line is executed, nothing is added to the ListView

What I have tried:

I added a button, when clicked, it successfully adds a ListViewItem to the ListView object, as it should. (this is before the worker thread start, for testing/debugging)

I have also tried swapping the ListView to a RichEdit in case I had a bug in the code, but the items successfully display in the RichEdit, thus I added another ListView incase the first/previous one was buggy, and without renaming the ListView, I tried adding the items, but without success.

What happens in the Delegate:

Nothing, after the clear() method, the 4 columns each with headers disappear and nothing is added to the list view

Conclusion:

My only conclusion is that the delegate is not compatible with the ListView, since I was able to add the items to a RichEdit, but not to a ListView.

Is this a bug? Am I doing something wrong?

code sample

void connected_add_device()
        {
            string[] t = { "123", "-1", "sa.d.sdf.s.fg", "sda-f-sd-fgds-gf" };
            if (display_connected_Devices.InvokeRequired)
                display_connected_Devices.BeginInvoke((MethodInvoker)delegate ()
                {
                    display_connected_Devices.Clear();
                    display_connected_Devices.Items.Add(new ListViewItem(t));
                }
                );
            else
            {
                display_connected_Devices.Clear();
                display_connected_Devices.Items.Add(new ListViewItem(t));
            }
        }

For what it is worth, I had a bad GIT commit. After everthing is fixed, this ListView (which before the GIT issue, had successfuly displayed the items) now doesn't display the items anymore.

Use display_connected_Devices.Items.Clear(); instead. Because display_connected_Devices.Clear(); will clear, like you noticed, the columns aswell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM