Search code examples
c#winformslistviewblank-line

How to prevent a listview from adding a blank line?


Currently this is my code.

        TextReader reader = new StringReader(richTextBox1.Text);
        string[] strItems = null;
        while (reader.Peek() != -1)
        {
            string nextRow = reader.ReadLine();
            if (!listView1.Items.ContainsKey(nextRow.GetHashCode().ToString()))
            {
                ListViewItem item = new ListViewItem();
                item.Name = nextRow.GetHashCode().ToString();
                strItems = nextRow.Split("-".ToCharArray());
                item.Text = strItems[0].ToString();
                try
                {
                    item.SubItems.Add(strItems[1].ToString());
                }
                catch (Exception)
                {
                }
                try
                {
                    item.SubItems.Add(strItems[2].ToString());
                }
                catch (Exception)
                {
                }
                try
                {
                    item.SubItems.Add(strItems[3].ToString());
                }
                catch (Exception)
                {
                }
                try
                {
                    item.SubItems.Add(strItems[4].ToString());
                }
                catch (Exception)
                {
                }
                listView1.Items.Add(item);
            }
        }

It add's Items from a textbox to a ListView, but if there is a Blank line in the textbox it also adds a blank item to the listview. I am looking for a way to stop this from happening. All help is appreciated.


Solution

  • Add an if to check that:

    if(!string.IsNullOrEmpty(nextRow)) {
       execute the code you need
    }