How do I make a data grid in .Net and print a data grid

How do I make a data grid in .Net and print a data grid
1030071002Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

khan_webguruCommented:
Please see the code below step by step

Createin ASPX (.Net page)

 
<%@ Page Language = "C#" %>
<%@ Import Namespace = "System.Data" %>

<html>
  <head>
    <title>DataGrid Sample</title>
    
    
  </head>
    
  <body>
    <asp:DataGrid id = "myGrid"
                  CellPadding = "5"
                  AutoGenerateColumns = "false"
                  Font-Name = "verdana"
                  Font-Size = "10pt"
                  runat = "server">
                  
      <HeaderStyle BackColor = "#336699" 
                 ForeColor = "#ffffff" Font-Bold = "true" />      
      <AlternatingItemStyle BackColor = "#eeeeee" />
                  
      <Columns>
        <asp:BoundColumn HeaderText = "First Name" 
                            DataField = "firstName" />
        <asp:BoundColumn HeaderText = "Last Name" 
                            DataField = "lastName" />
        <asp:BoundColumn HeaderText = "Email" 
                            DataField = "emailAddress" />
      </Columns>
    </asp:DataGrid>
  </body>
</html>

Open in new window


See the code behind for binding that grid to some data

 
private void Page_Load(object sender, EventArgs e)
      {
        if (!Page.IsPostBack)
          BindGrid();
      }
      
      private void BindGrid()
      {
        DataTable table = new DataTable("Users");
        table.Columns.Add("firstName");
        table.Columns.Add("lastName");
        table.Columns.Add("emailAddress");
        
        AddRow(table, "Bugs", "Bunny", "bbunny@wb.com");
        AddRow(table, "Mickey", "Mouse", "mmouse@disney.com");
        AddRow(table, "Donald", "Duck", "dduck@disney.com");
        AddRow(table, "Dan", "Marino", "dmarino@dolphins.com");
        AddRow(table, "Steve", "Stchur", "sstchur@yahoo.com");
        
        myGrid.DataSource = new DataView(table);
        myGrid.DataBind();        
      }
      
      private void AddRow(DataTable table, string firstName, 
                          string lastName, string email)
      {
        DataRow row = table.NewRow();
        row["firstName"] = firstName;
        row["lastName"] = lastName;
        row["emailAddress"] = email;
        table.Rows.Add(row);
      }

Open in new window


Handling Print button

 
protected void OnPrint(object sender, EventArgs e)
{
    m_obPrtMgr = new PrintManager();

    PRT2DISKLib.Print2DiskClass pdfServer = new PRT2DISKLib.Print2DiskClass();
    String strPdfFile = Server.MapPath("~/PdfReports");
    pdfServer.PDFAuthor = "Winista";
    pdfServer.OutputDirectory = strPdfFile;
    pdfServer.NewDocumentName = Guid.NewGuid().ToString("N") + ".pdf";
    strPdfFile = System.IO.Path.Combine(strPdfFile, pdfServer.DocumentName);
    pdfServer.GeneralFlags += 16;

    PrintDocument doc = new PrintDocument();
    doc.PrintPage += new PrintPageEventHandler(this.Print);
    pdfServer.PrintQuality = -4;	// High resolution
    int iRetVal = pdfServer.StartPrinting();
    doc.PrinterSettings.PrinterName = pdfServer.NewPrinterName;
    SetupTextReport(m_obPrtMgr);
    doc.Print();
    pdfServer.Wait(1);
    pdfServer.StopPrinting();
    strPdfFile = "/PdrRefports/" + pdfServer.DocumentName;
    pdfServer = null;
    RegisterScriptForReportDisplay(strPdfFile);
}

Open in new window


Setting up grid printing layout

 
private PrintDataTable PrepareDataTable(DataTable dtable)
{
    PrintDataTable dt = new PrintDataTable();
    dt.DrawTableHeader = true;
    dt.DataSource = dtable.DefaultView;

    // Add column information.
    PrintDataColumnCollection cols = dt.Columns;

    PrintDataColumn col = new PrintDataColumn("ProductID", 1.25f, StringAlignment.Far);
    col.HeaderBackColor = Color.Gainsboro;
    col.BackColor = Color.Aquamarine;
    col.HeaderText = "Product ID";
    col.HeaderAlignment = StringAlignment.Center;
    cols.Add(col);

    col = new PrintDataColumn("Name", 1.25f, StringAlignment.Near);
    col.HeaderBackColor = Color.Gainsboro;
    col.ForeColor = Color.Blue;
    col.HeaderText = "Product Name";
    col.HeaderAlignment = StringAlignment.Center;
    cols.Add(col);

    col = new PrintDataColumn("ListPrice", 1.25f, StringAlignment.Far);
    col.HeaderText = "List Price";
    col.HeaderBackColor = Color.Gainsboro;
    col.HeaderAlignment = StringAlignment.Center;
    col.FormatDataColumn += new FormatDataColumnEventHandler(this.FormatDateColumn);
    cols.Add(col);

    return dt;
}

Open in new window


hope this will help you

Regards,

AAK

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.