ByteScout BarCode Generator SDK - Crystal Reports - generate Report from SQL Server C# 2015 - ByteScout
Announcement
Our ByteScout SDK products are sunsetting as we focus on expanding new solutions.
Learn More Open modal
Close modal
Announcement Important Update
ByteScout SDK Sunsetting Notice
Our ByteScout SDK products are sunsetting as we focus on our new & improved solutions. Thank you for being part of our journey, and we look forward to supporting you in this next chapter!

ByteScout BarCode Generator SDK – Crystal Reports – generate Report from SQL Server C# 2015

  • Home
  • /
  • Articles
  • /
  • ByteScout BarCode Generator SDK – Crystal Reports – generate Report from SQL Server C# 2015

ByteScout BarCode Generator SDK – Crystal Reports – generate Report from SQL Server C# 2015

CrystalReport1.cs

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ReportFromSqlServer {
    using System;
    using System.ComponentModel;
    using CrystalDecisions.Shared;
    using CrystalDecisions.ReportSource;
    using CrystalDecisions.CrystalReports.Engine;
    
    
    public class CrystalReport1 : ReportClass {
        
        public CrystalReport1() {
        }
        
        public override string ResourceName {
            get {
                return "CrystalReport1.rpt";
            }
            set {
                // Do nothing
            }
        }
        
        public override bool NewGenerator {
            get {
                return true;
            }
            set {
                // Do nothing
            }
        }
        
        public override string FullResourceName {
            get {
                return "ReportFromSqlServer.CrystalReport1.rpt";
            }
            set {
                // Do nothing
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
        public CrystalDecisions.CrystalReports.Engine.Section Section1 {
            get {
                return this.ReportDefinition.Sections[0];
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
        public CrystalDecisions.CrystalReports.Engine.Section Section2 {
            get {
                return this.ReportDefinition.Sections[1];
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
        public CrystalDecisions.CrystalReports.Engine.Section Section3 {
            get {
                return this.ReportDefinition.Sections[2];
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
        public CrystalDecisions.CrystalReports.Engine.Section Section4 {
            get {
                return this.ReportDefinition.Sections[3];
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
        public CrystalDecisions.CrystalReports.Engine.Section Section5 {
            get {
                return this.ReportDefinition.Sections[4];
            }
        }
    }
    
    [System.Drawing.ToolboxBitmapAttribute(typeof(CrystalDecisions.Shared.ExportOptions), "report.bmp")]
    public class CachedCrystalReport1 : Component, ICachedReport {
        
        public CachedCrystalReport1() {
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
        public virtual bool IsCacheable {
            get {
                return true;
            }
            set {
                // 
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
        public virtual bool ShareDBLogonInfo {
            get {
                return false;
            }
            set {
                // 
            }
        }
        
        [Browsable(false)]
        [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
        public virtual System.TimeSpan CacheTimeOut {
            get {
                return CachedReportConstants.DEFAULT_TIMEOUT;
            }
            set {
                // 
            }
        }
        
        public virtual CrystalDecisions.CrystalReports.Engine.ReportDocument CreateReport() {
            CrystalReport1 rpt = new CrystalReport1();
            rpt.Site = this.Site;
            return rpt;
        }
        
        public virtual string GetCustomizedCacheKey(RequestContext request) {
            String key = null;
            // // The following is the code used to generate the default
            // // cache key for caching report jobs in the ASP.NET Cache.
            // // Feel free to modify this code to suit your needs.
            // // Returning key == null causes the default cache key to
            // // be generated.
            // 
            // key = RequestContext.BuildCompleteCacheKey(
            //     request,
            //     null,       // sReportFilename
            //     this.GetType(),
            //     this.ShareDBLogonInfo );
            return key;
        }
    }
}

Form1.cs

using System;
using System.Data;
using System.Diagnostics;
using System.Windows.Forms;
using System.Data.SqlClient;
using Bytescout.BarCode;

namespace ReportFromSqlServer
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();

			try
			{
				// MODIFY THE CONNECTION STRING WITH YOUR SERVER CONNECTION INFO!!!
				const string connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=master;Integrated Security=true;";

				using (SqlConnection connection = new SqlConnection(connectionString))
				{
					connection.Open();

					// Create a database for demonstration purposes
					///////////////////////////////////////////////////////////////////////////////////////

					Object o = ExecuteQueryScalar(connection, "SELECT DB_ID('example_db')");

					// if 'example_db' does not exist, create it
					if (o == null || o is DBNull)
					{
						// Create empty database
						ExecuteQueryWithoutResult(connection, "CREATE DATABASE example_db");
						// Switch to created database
						ExecuteQueryWithoutResult(connection, "USE example_db");
						// Create a table
						ExecuteQueryWithoutResult(connection, "CREATE TABLE Products ([Product ID] int, [Product Name] nvarchar(100), [Product Description] nvarchar(255))");
						// Fill the table with data
						ExecuteQueryWithoutResult(connection, "INSERT Products VALUES(1, 'Spreadsheet Tools', 'Convert XLS, XLSX, CSV, ODS spreadsheet into HTML, PDF, XLS, XLSX, CSV formats WITHOUT EXCEL installed')");
						ExecuteQueryWithoutResult(connection, "INSERT Products VALUES(2, 'Watermarking PRO', 'Professional tool to protect images: multiple watermarks, custom position for watermarks, image effects, EXIF and IPTC macros for text and more')");
						ExecuteQueryWithoutResult(connection, "INSERT Products VALUES(3, 'Watermarking', 'Protect copyrights for your images with professional looking watermarks with this easy to use tool')");
						ExecuteQueryWithoutResult(connection, "INSERT Products VALUES(4, 'PPT To Video Scout', 'converts PowerPoint presentations (PPT, PPTX) into AVI,MPEG,WMV, FLV (flash video) video movies with sound')");
					}


					// Create a datataset from query.
					// Query result columns must conform to field names we used in the report designer

					SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT [Product ID], [Product Name], [Product Description] FROM example_db.dbo.Products", connection);

					// fill dataset
					DataSet dataSet = new DataSet();
					dataAdapter.Fill(dataSet);

					// don't forget to close the connection
					connection.Close();

					// add virtual column into the result table
					dataSet.Tables[0].Columns.Add(new DataColumn("BarCode", typeof(byte[])));

					// create barcode object
					Barcode bc = new Barcode(SymbologyType.Code39);
					bc.DrawCaption = false;

					foreach (DataRow row in dataSet.Tables[0].Rows)
					{
						// set barcode value
						bc.Value = (Convert.ToString(row["Product ID"]));

						// retrieve generated image bytes
						byte[] barcodeBytes = bc.GetImageBytesWMF();

						// fill virtual column with generated image bytes
						row["BarCode"] = barcodeBytes;
					}

					// set report datasource
					CrystalReport11.SetDataSource(dataSet.Tables[0]);
				}
			}
			catch (Exception ex)
			{
				Trace.WriteLine("Error: " + ex.Message);
			}
		}

		private static void ExecuteQueryWithoutResult(SqlConnection connection, string query)
		{
			using (SqlCommand command = new SqlCommand(query, connection))
			{
				command.ExecuteNonQuery();
			}
		}

		private static object ExecuteQueryScalar(SqlConnection connection, string query)
		{
			using (SqlCommand command = new SqlCommand(query, connection))
			{
				return command.ExecuteScalar();
			}
		}
	}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace ReportFromSqlServer
{
	static class Program
	{
		[STAThread]
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.Run(new Form1());
		}
	}
}

DataSet1.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="DataSet1" targetNamespace="http://tempuri.org/DataSet1.xsd" xmlns:mstns="http://tempuri.org/DataSet1.xsd" xmlns="http://tempuri.org/DataSet1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop" attributeFormDefault="qualified" elementFormDefault="qualified">
  <xs:annotation>
    <xs:appinfo source="urn:schemas-microsoft-com:xml-msdatasource">
      <DataSource DefaultConnectionIndex="0" FunctionsComponentName="QueriesTableAdapter" Modifier="AutoLayout, AnsiClass, Class, Public" SchemaSerializationMode="IncludeSchema" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
        <Connections>
          <Connection AppSettingsObjectName="Settings" AppSettingsPropertyName="example_dbConnectionString" ConnectionStringObject="" IsAppSettingsProperty="True" Modifier="Assembly" Name="example_dbConnectionString (Settings)" ParameterPrefix="@" PropertyReference="ApplicationSettings.ReportFromSqlServer.Properties.Settings.GlobalReference.Default.example_dbConnectionString" Provider="System.Data.SqlClient">
          </Connection>
        </Connections>
        <Tables>
          <TableAdapter BaseClass="System.ComponentModel.Component" DataAccessorModifier="AutoLayout, AnsiClass, Class, Public" DataAccessorName="ProductsTableAdapter" GeneratorDataComponentClassName="ProductsTableAdapter" Name="Products" UserDataComponentName="ProductsTableAdapter">
            <MainSource>
              <DbSource ConnectionRef="example_dbConnectionString (Settings)" DbObjectName="example_db.dbo.Products" DbObjectType="Table" FillMethodModifier="Public" FillMethodName="Fill" GenerateMethods="Both" GenerateShortCommands="True" GeneratorGetMethodName="GetData" GeneratorSourceName="Fill" GetMethodModifier="Public" GetMethodName="GetData" QueryType="Rowset" ScalarCallRetval="System.Object, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" UseOptimisticConcurrency="True" UserGetMethodName="GetData" UserSourceName="Fill">
                <InsertCommand>
                  <DbCommand CommandType="Text" ModifiedByUser="False">
                    <CommandText>INSERT INTO [dbo].[Products] ([Product ID], [Product Name], [Product Description]) VALUES (@Product_ID, @Product_Name, @Product_Description)</CommandText>
                    <Parameters>
                      <Parameter AllowDbNull="True" AutogeneratedName="" DataSourceName="" DbType="Int32" Direction="Input" ParameterName="@Product_ID" Precision="0" ProviderType="Int" Scale="0" Size="0" SourceColumn="Product ID" SourceColumnNullMapping="False" SourceVersion="Current">
                      </Parameter>
                      <Parameter AllowDbNull="True" AutogeneratedName="" DataSourceName="" DbType="String" Direction="Input" ParameterName="@Product_Name" Precision="0" ProviderType="NVarChar" Scale="0" Size="0" SourceColumn="Product Name" SourceColumnNullMapping="False" SourceVersion="Current">
                      </Parameter>
                      <Parameter AllowDbNull="True" AutogeneratedName="" DataSourceName="" DbType="String" Direction="Input" ParameterName="@Product_Description" Precision="0" ProviderType="NVarChar" Scale="0" Size="0" SourceColumn="Product Description" SourceColumnNullMapping="False" SourceVersion="Current">
                      </Parameter>
                    </Parameters>
                  </DbCommand>
                </InsertCommand>
                <SelectCommand>
                  <DbCommand CommandType="Text" ModifiedByUser="False">
                    <CommandText>SELECT [Product ID], [Product Name], [Product Description] FROM dbo.Products</CommandText>
                    <Parameters>
                    </Parameters>
                  </DbCommand>
                </SelectCommand>
              </DbSource>
            </MainSource>
            <Mappings>
              <Mapping SourceColumn="Product ID" DataSetColumn="Product ID" />
              <Mapping SourceColumn="Product Name" DataSetColumn="Product Name" />
              <Mapping SourceColumn="Product Description" DataSetColumn="Product Description" />
            </Mappings>
            <Sources>
            </Sources>
          </TableAdapter>
        </Tables>
        <Sources>
        </Sources>
      </DataSource>
    </xs:appinfo>
  </xs:annotation>
  <xs:element name="DataSet1" msdata:IsDataSet="true" msdata:UseCurrentLocale="true" msprop:Generator_UserDSName="DataSet1" msprop:Generator_DataSetName="DataSet1">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Products" msprop:Generator_UserTableName="Products" msprop:Generator_RowDeletedName="ProductsRowDeleted" msprop:Generator_RowChangedName="ProductsRowChanged" msprop:Generator_RowClassName="ProductsRow" msprop:Generator_RowChangingName="ProductsRowChanging" msprop:Generator_RowEvArgName="ProductsRowChangeEvent" msprop:Generator_RowEvHandlerName="ProductsRowChangeEventHandler" msprop:Generator_TableClassName="ProductsDataTable" msprop:Generator_TableVarName="tableProducts" msprop:Generator_RowDeletingName="ProductsRowDeleting" msprop:Generator_TablePropName="Products">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Product_x0020_ID" msprop:Generator_UserColumnName="Product ID" msprop:Generator_ColumnVarNameInTable="columnProduct_ID" msprop:Generator_ColumnPropNameInRow="Product_ID" msprop:Generator_ColumnPropNameInTable="Product_IDColumn" type="xs:int" minOccurs="0" />
              <xs:element name="Product_x0020_Name" msprop:Generator_UserColumnName="Product Name" msprop:Generator_ColumnVarNameInTable="columnProduct_Name" msprop:Generator_ColumnPropNameInRow="Product_Name" msprop:Generator_ColumnPropNameInTable="Product_NameColumn" minOccurs="0">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:maxLength value="100" />
                  </xs:restriction>
                </xs:simpleType>
              </xs:element>
              <xs:element name="Product_x0020_Description" msprop:Generator_UserColumnName="Product Description" msprop:Generator_ColumnVarNameInTable="columnProduct_Description" msprop:Generator_ColumnPropNameInRow="Product_Description" msprop:Generator_ColumnPropNameInTable="Product_DescriptionColumn" minOccurs="0">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:maxLength value="255" />
                  </xs:restriction>
                </xs:simpleType>
              </xs:element>
              <xs:element name="BarCode" msprop:Generator_UserColumnName="BarCode" msprop:Generator_ColumnVarNameInTable="columnBarCode" msprop:Generator_ColumnPropNameInRow="BarCode" msprop:Generator_ColumnPropNameInTable="BarCodeColumn" type="xs:base64Binary" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

  Click here to get your Free Trial version of the SDK

Tutorials:

prev
next