【问题标题】:Getting data from datagridview to string从datagridview获取数据到字符串
【发布时间】:2011-08-05 19:53:38
【问题描述】:

我想获取 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";
        }

【问题讨论】:

  • GridView 上的数据是否有任何改变?因为,如果是我,我会获取实际填充网格的数据对象并循环遍历它。
  • 不幸的是,datagridview 中的数据来自无数来源(表格和用户输入)。我的意图是从不同来源获取所有数据,将它们全部放在可见控件中,以便用户可以查看它,然后根据需要打印它。

标签: c# string datagridview


【解决方案1】:

我建议使用更通用的方法来执行此操作,这样您以后就不必重写它。这也与您的 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();
    }

【讨论】:

  • 这是一个很好的小程序。我以前从未使用过 StringBuilder 类,所以这对我来说很有趣。谢谢!
  • 不客气。 StringBuilders 在将一堆小字符串连接在一起的内存和速度方面效率更高。如果您要将> 3个左右的字符串连接在一起,我总是会使用它们。
【解决方案2】:

试试这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 2020-11-06
    • 2021-05-31
    • 2013-09-26
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多