E
E
Emil2022-04-18 17:54:22
Windows
Emil, 2022-04-18 17:54:22

Why are no items shown in the ListView and is also null?

Hello. I am writing a C# program using Windows Forms, and there was a problem - the items in the ListView are not updated (Items).
I'm trying to update items. I get an error that the ListView is null. Why is this happening?
Display type - Details. Why is this happening?
The code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.NetworkInformation;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces())
            {
                Console.WriteLine("Network Interface: {0}", netif.Name);
                IPInterfaceProperties properties = netif.GetIPProperties();
                foreach (IPAddressInformation unicast in properties.UnicastAddresses)
                {
                    string item = unicast.Address.ToString();
                    try
                    {
                        if (item != null)
                        {
                            Console.WriteLine(item);
                            listView1.Items.Add(item,item,0);
                            listView1.Update();
                        }
                    }
                    catch (NullReferenceException)
                    {
                        Console.WriteLine("Error!");
                    }
                }
                
            }
                listView1.Update();
         InitializeComponent();
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nik Faraday, 2022-04-23
@MrCheatEugene

The given class in which you write (Form1) is partial (Read about it). The second part of this class initializes (i.e. creates) all components (Buttons, TextBoxes, etc.) on the form. Therefore, before at least some elements appear on the form, they cannot be, because. technically, they won't exist at all yet (i.e. null)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question