从DataGridView到多行逗号分隔的字符串

时间:2012-06-24 09:20:27

标签: c# winforms string datagridview

我有一个带有四个列的DataGridView,需要从其内容中创建一个多行字符串,用逗号分隔。
这段代码可行,但可能 - 有一种更优雅的方式:

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

2 个答案:

答案 0 :(得分:3)

我不知道优雅,但是:

  1. 使用StringBuilder 进行字符串操作,类型字符串是不可变的!
  2. 如果您需要在两者之间执行某些操作,请将第一个或最后一个循环分开(例如逗号分隔) 所以,基本上是这样的:
  3. 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();
      }
     }
    }

    为了说明StringBuilder连接(只是动态字符数组)和字符串(每次使用operator + concatenation时新对象和复制所有内容)之间的速度差异,请查看迷你程序:

    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.");
    }

    我的电脑是:

    using version with type String I did 17682 times of string concatenation.
    using version with type StringBuilder I did 366367 times of string concatenation.

答案 1 :(得分:0)

试试这个:

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