将数据从datagridview获取到字符串

Kev*_*vin 2 c# string datagridview

我想在datagridview中获取每一行并将其添加到一个字符串变量,然后我将使用自定义PrintDocument类进行打印.我的程序中的所有内容都可以工作,除了将datagridview中的数据转换为字符串变量.我找不到一个如何做到这一点的例子.我不是只使用"foreach(dataGridView1中的DataRow Row)..."循环数据表并将其添加到我的字符串变量中吗?有人能给我看一个例子吗?

现在,我的代码看起来像这样,但它不会编译(在我尝试从column.row获取值到字符串的方式上获取错误消息.错误消息是"最佳重载方法匹配对于'System.Windows.Form.DataGridViewRowCollection.This [int]'有一些无效的参数):

        //Loop through the dataGridView1 and add it to the text
        //that we want to print
        foreach (DataRow row in dataGridView1.Rows)
        {
            textToPrint = textToPrint + dataGridView1.Rows[row][0].ToString() + "\t" +
                dataGridView1.Rows[row][1].ToString() + "\t" +
                dataGridView1.Rows[row][2].ToString() + "\t" +
                dataGridView1.Rows[row][3].ToString() + "\t";
        }
Run Code Online (Sandbox Code Playgroud)

Moo*_*oop 6

我建议使用更通用的方法来执行此操作,以便将来不必重写它.这也与您可能拥有的列数无关DataGridView.

    public static string DGVtoString(DataGridView dgv, char delimiter)
    {
        StringBuilder sb = new StringBuilder();
        foreach (DataGridViewRow row in dgv.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                sb.Append(cell.Value);
                sb.Append(delimiter);
            }
            sb.Remove(sb.Length - 1, 1); // Removes the last delimiter 
            sb.AppendLine();
        }
        return sb.ToString();
    }
Run Code Online (Sandbox Code Playgroud)