C# 从DataGridView到StringBuilder obj

C# 从DataGridView到StringBuilder obj,c#,datagridview,stringbuilder,C#,Datagridview,Stringbuilder,我有一个DataGridView(dgv1),其中加载了一些数据。我想循环dgv1并将特定列(0、1、3和4)中的数据附加到StringBuilder对象(sb)中。我想象它会像这样: // Add data to the StringBuilder int currentRow = 0; StringBuilder temp = new StringBuilder(); foreach (DataGridViewRow row i

我有一个DataGridView(dgv1),其中加载了一些数据。我想循环dgv1并将特定列(0、1、3和4)中的数据附加到StringBuilder对象(sb)中。我想象它会像这样:

        // Add data to the StringBuilder
        int currentRow = 0;
        StringBuilder temp = new StringBuilder();
        foreach (DataGridViewRow row in dgv1.Rows)
        {
            foreach (DataGridViewColumn col in dgv1.Columns)
            {
                temp.Append(dataGridView2.Rows[currentRow].Cells[col].Value.ToString());
                currentRow++;
            }
        }

然而,我不认为这是完全正确的。有人能提供一些建议吗?

老实说,不要认为这是不对的

我可以考虑的一件事是,如果使用数据绑定绑定到DataGrid,则迭代数据绑定值,而不是UI控件内容。在这种情况下,您可能会使用LINQ,这将导致更清晰的代码

问候。

您不需要这个:

dataGridView2.Rows[currentRow]
因为相同的对象已在此处:

dgr

通过这种方式直接使用
dgr
,您可以简化对
currentRow

的处理,当然,正如Tigran所说,与数据源相比,直接迭代比使用UI控件更好……)那是个好主意。我不反对控件,我可以反对它的数据源。谢谢