2011-08-05 133 views
1

我想获取datagridview中的每一行并将其添加到字符串变量,然后使用自定义PrintDocument类进行打印。除了将datagridview中的数据导入字符串变量之外,我的程序中的所有内容都可以工作。我找不到如何做到这一点的例子。我不会只是使用“foreach(dataRow Row in dataGridView1)...”循环访问数据表并将其添加到我的字符串变量中吗?有人能告诉我一个这样的例子吗?从datagridview获取数据到字符串

现在,我的代码看起来像这样,但它不会编译(获取错误消息的方式我试图从column.row中获取值到字符串中。错误消息是“The最好重载方法匹配关于 '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"; 
     } 
+0

数据是否以任何方式在GridView上改变?因为,如果是我,我会采用实际填充网格并循环的数据对象。 – Zensar

+0

不幸的是,datagridview中的数据来自无数来源(表格和用户输入)。我的意图是从不同来源获取所有数据,并将其全部放在可见的控件中,以便用户查看并打印出来(如果他们愿意的话)。 – Kevin

回答

4

我建议使用更通用的方法来做到这一点,以便您不必在将来重写它。这也将与您在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(); 
    } 
+0

这是一个很好的小例程。我以前从来没有使用过StringBuilder类,所以这对我来说非常有趣。谢谢! – Kevin

+0

不客气。 StringBuilders在将大量小字符串连接在一起的内存和速度方面效率更高。如果你打算加入> 3个左右的字符串,我总是会使用它们。 – Moop

0
尝试

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