0

I have a DataGridView with four Columns and need to crate a multiline string from its content, separated by comma.
This code works, but probably - there is a more elegant way:

string multiLine = "";
string singleLine;    
foreach (DataGridViewRow r in dgvSm.Rows)
{
    if (!r.IsNewRow)
    {
        singleLine = r.Cells[0].Value.ToString() + ","
        + r.Cells[1].Value.ToString() + ","
        + r.Cells[2].Value.ToString() + ","
        + r.Cells[3].Value.ToString() + Environment.NewLine;
        multiLine = multiLine + singleLine;
    }
}
David Hall
  • 32,624
  • 10
  • 90
  • 127
Buena
  • 2,461
  • 2
  • 20
  • 22

2 Answers2

3

I don't know about elegant, but:

  1. use StringBuilder for string manipulation, type string is immutable!
  2. if you need to do something in between, separate first or last cycle running (e.g. comma separation) So, basically something like this:
StringBuilder multiLine = new StringBuilder();
foreach (DataGridViewRow r in dgvSm.Rows)
{
 if (!r.IsNewRow)
 {
  if (r.Cells.Count > 0)
  {
   multiLine.Append(r.Cells[0].Value.ToString()); //first separated
   for (int i = 1; i < r.Cells.Count; ++i)
   {
    singleLine.Append(','); //between values
    singleLine.Append(r.Cells[i].Value.ToString());
   }
   multiLine.AppendLine();
  }
 }
}

To illustrate speed difference between StringBuilder concatenation (just dynamic array of characters) and string (new object and copy everything each time you use operator + concatenation), have a look at mini-program:

public static void Main()
{
    var sw = new Stopwatch();
    sw.Start();
    StringBuilder s = new StringBuilder();
    //string s = "";
    int i;
    for (i = 0; sw.ElapsedMilliseconds < 1000; ++i)
        //s += i.ToString();
        s.Append(i.ToString());
    sw.Stop();
    Console.WriteLine("using version with type " + s.GetType().Name + " I did " +
        i + " times of string concatenation.");
}

For my computer it is:

using version with type String I did 17682 times of string concatenation.
using version with type StringBuilder I did 366367 times of string concatenation.
peenut
  • 3,366
  • 23
  • 24
  • peenut, maybe your code takes more processing time than the first one (if a dgv has 1000 rows, for example. What do you think? – Buena Jun 24 '12 at 09:46
  • Buena, I added code to compare string and StringBuilder speed – peenut Jun 24 '12 at 09:58
0

Try this :

    string multiLine = "";
string singleLine;    
foreach (DataGridViewRow r in dgvSm.Rows)
{
if (!r.IsNewRow)
{
singleLine = r.Cells[0].Value.ToString() + ","
+ r.Cells[1].Value.ToString() + ","
+ r.Cells[2].Value.ToString() + ","
+ r.Cells[3].Value.ToString() + "\r\n";
multiLine = multiLine + singleLine;
}
}
Ali Vojdanian
  • 2,067
  • 2
  • 31
  • 47