Impin aint easy Impin aint easy - 28 days ago 16
C# Question

Convert ListView to Line separated String Array and vice versa

I am trying to take all items in my ListView and write each one into a new line inside a string Array (or something similar). This is so i can pass these values to a string property inside an object that is then saved to a SQL Database (Varchar(max)).

What i have tried sofar

public string ConvertToString(ListView l)
{
ArrayList list = new ArrayList();

foreach (string item in l.Items)
{
list.Add(item);
}

return list.ToString();
}


but im obviously missing the newline split which i am struggling with.
The current code only saves "System.Collections.ArrayList" into the database.

I also did alot of googling and keep coming across "string[]" but thats no good as i have to predefine the length, which i dont know as it keeps changing when items get added to the ListView.

I also need a reverse method when reading the values from the database to put each line back into the ListView.

Any help is much appreciated.

Answer

StringBuilder perfectly saves the CR/LF chars.

  public string ConvertToString(ListView l)
  {
     StringBuilder list = new StringBuilder();

     foreach (string item in l.Items)
        list.AppendLine(item);

     return list.ToString();
  }

Reverse is similar:

  public voidConvertToString(ListView l, string dbString)
  {
     string [] sep = {"\r\n"};
     foreach (string item in dbString.Split(sep, StringSplitOptions.None))
        l.Items.Add(item);
  }