C# ListViewItems is not returning empty

159 views Asked by At

I am using this method and it keeps saying listView1 has items even though none appear in the listview?

        private void button8_Click(object sender, EventArgs e)
    {
        string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\test.txt";
        if (Directory.Exists(filePath))
        {
            listView1.Items.Clear();

            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                using (TextReader sr = new StreamReader(fs))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] data = line.Split(new char[] { ',' });
                        ListViewItem lvi = new ListViewItem();

                        if (listView1.Items.Count > 0)
                        {
                            MessageBox.Show("ListViewCount#1: '" + listView1.Items.Count + "'.");
                        }

                        lvi.Text = data[0];
                        lvi.SubItems.Add(data[1]);
                        lvi.SubItems.Add(data[3]);
                        lvi.SubItems.Add(data[4]);
                        lvi.Tag = data[2];

                        listView1.Items.Add(lvi);

                        if (listView1.Items.Count > 0)
                        {
                            MessageBox.Show("ListViewCount#2: '" + listView1.Items.Count + "'.");
                        }
                    }
                }
            }
            if (listView1.Items.Count == 0)
            {
                MessageBox.Show("ERROR: ListView has no data to show.");
                return;
            }
        }
    }

The listView1.count is more than 0 after the "lvi" part, prior to that it is empty(tested with messagebox counting listView1 before and after this method), why is it saying it has a "listView1.count of 1" if all the "data" is empty? I have tried other ways to work around this using custom booleans in other methods but its just not practical referring back to them, all i want to do is if listview1 is 0 tell user there is no data.

1

There are 1 answers

0
Fuzzybear On

You must have initialised you listview earlier in the code so as to not get a runtime error at:

listView1.Items.Add(lvi);

The instantiation of the listview will create an empty listview with a count of 0 thus passing your if declaration.