Buena
Buena

Reputation: 2491

From DataGridView to multiline commaSeparated string

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;
    }
}

Upvotes: 0

Views: 1391

Answers (2)

peenut
peenut

Reputation: 3426

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.

Upvotes: 3

Ali Vojdanian
Ali Vojdanian

Reputation: 2111

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;
}
}

Upvotes: 0

Related Questions