LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to print a data grid in visual C#? (https://www.linuxquestions.org/questions/programming-9/how-to-print-a-data-grid-in-visual-c-438635/)

mrobertson 04-25-2006 08:18 AM

How to print a data grid in visual C#?
 
Does anyone know how to print a data grid in visual C#? My particular datagrid has close to 50 columns. I have tried the code on MSDN, c sharp corner, and code project but niether seem to account for the additional columnspast the viewable area on the form of the data grid. Hence only 10 columns actually print. Can anyone help me with this?

Vagrant 04-25-2006 12:11 PM

Why not just print it plain-text tab delimited data?

mrobertson 04-26-2006 07:13 AM

How would you go about do that? I am not familiar with that kind of thing.

Vagrant 04-26-2006 01:15 PM

Well, its pretty simple.

Code:

DataTable dt = (DataTable)dataGrid.DataSource;

string output = "";
foreach(DataRow dr in dt.Rows)
{
      bool isFirst = true;
      foreach(DataColumn dc in dt.Columns)
      {
          if(!isFirst)
              output += "\t";
          output += dr[dc].ToString();
          isFirst = false;
      }
      output += "\r\n";
}

Something along those lines.

mrobertson 04-27-2006 10:04 AM

Here is the code I am trying to use. I am getting a specified cast is not valid error on the first line of code. What do you see that may be causing this. Is there anything that I need to change or add. Also what will this look like when completed and printed?
Code:

System.Data.DataTable dt = (System.Data.DataTable)dataGrid.DataSource;
                       
                        string output = "";
                        foreach(DataRow dr in dt.Rows)
                        {
                                bool isFirst = true;
                                foreach(DataColumn dc in dt.Columns)
                                {
                                        if(!isFirst)
                                                output += "\t";
                                        output += dr[dc].ToString();
                                        isFirst = false;
                                }
                                output += "\r\n";

}

Vagrant 04-27-2006 12:47 PM

Well, it depends on what exactly the dataGrid.DataSource is. You need to know that before you continue with this part of the code. Perhaps it is an entire dataset, which would mean you would have to change the code to something like this:

System.Data.DataTable dt = ((System.Data.DataSet)dataGrid.DataSource).Tables[0]; // or which ever table you need

mrobertson 04-28-2006 07:55 AM

Ok, I am making progress, however I still cannot print. I have populated output but I now need to have a nice and neat printed document formatted with headers as well. How can this be done?


All times are GMT -5. The time now is 01:32 PM.