从datagridview获取数据到字符串

本文关键字:字符串 数据 获取 datagridview | 更新日期: 2023-09-27 18:04:34

我想取datagridview中的每一行,并将其添加到一个字符串变量中,然后使用自定义PrintDocument类打印该变量。除了从datagridview获取数据到字符串变量之外,我的程序中的一切都工作正常。我找不到这样做的例子。难道我不只是使用"foreach(DataRow行在dataGridView1)…"循环通过数据表,并将其添加到我的字符串变量?有人能给我举个例子吗?

现在,我的代码看起来像这样,但是它不会编译(在我试图从列中获取值的过程中得到错误消息)。行到字符串中。错误信息是"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";
        }

从datagridview获取数据到字符串

我建议使用一种更通用的方法来完成此操作,以便将来不必重写它。这也与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();
    }

试试这个

dataGridView.Rows[RowIndex].Cells[ColumnIndex].Value as string

for (int row = 0 ; row < dataGridView1.Rows.Count; row ++)
{
    textToPrint = textToPrint + 
    dataGridView1.Rows[row].Cells[0].Value.ToString() + "'t" +
    dataGridView1.Rows[row].Cells[1].Value.ToString() + "'t" +
    dataGridView1.Rows[row].Cells[2].Value.ToString() + "'t" +
    dataGridView1.Rows[row].Cells[3].Value.ToString() + "'t";
}