跳至页脚内容
USING IRONBARCODE

How to Add a Barcode in Crystal Reports using C#

Crystal Reports is a powerful reporting tool that allows developers to create feature-rich reports for their applications. When it comes to including barcodes in Crystal Reports using C#, it adds a new dimension to data representation, making it easier to manage and track information. In this article, we'll explore the steps to integrate barcodes into Crystal Reports using C#.

How to Add a Barcode in Crystal Reports using C#

  1. Install the Barcode Library.
  2. Generate a Barcode image and save it as an image in a database table.
  3. Design the layout for the Crystal Report.
  4. Establish a connection to the database and select the necessary table.
  5. Include a Barcode Image field in the Crystal Report layout.
  6. Build and run the project.

Choose a Barcode Library

Before diving into the implementation, it's essential to select a barcode library that supports Crystal Reports and C#. One popular choice is the IronBarcode for .NET.

What is IronBarcode

IronBarcode is a versatile .NET library that simplifies barcode generation and reading. With IronBarcode, you can effortlessly create various barcodes, including Code 128 and QR codes, by specifying the value to encode. It also supports resizing and customization. On the reading side, IronBarcode can extract barcode data from images or PDFs, making it ideal for inventory management and document tracking. Its user-friendly API ensures quick integration into your projects, and cross-platform support allows seamless development across different .NET versions. Whether you’re a seasoned developer or a beginner, IronBarcode empowers you to work with barcodes efficiently.

Create a new Project

Open Visual Studio for creating an ASP.NET Crystal Reports Web Site. I am using Visual Studio 2022. You may use any, but make sure Crystal reports for Visual Studio for that particular version is installed.

How to Add a Barcode in Crystal Reports using C#: Figure 1 - Open Visual Studio. Create a new ASP.NET Crystal Reports Web Site project.

Select Project Name, Location & Target Framework. Click on the Create Button. A new Project will be created as shown below.

How to Add a Barcode in Crystal Reports using C#: Figure 2 - A new project will be created with a default CrystalReport1.rpt page.

Before we begin, we need to have a Database. Let's create a new database and a sample table.

Create a new Database

The following script will create a new database.

CREATE DATABASE ProductDB;
USE [ProductDB]
GO
/****** Object:  Table [dbo].[Products]    Script Date: 3/10/2024 2:57:18 PM******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Products](
    [Product_ID] [int] NULL,
    [Product_Name] [varchar](100) NULL,
    [Product_Price] [decimal](18, 0) NULL,
    [Product_Barcode] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Let's insert data into this table. We'll create a barcode and save it in the Product table. Therefore, we need to insert data using C# code and install the IronBarcode Library in our project to use its features to create barcodes.

Install IronBarcode Library

To install the IronBarcode library using the NuGet Package Manager Console, follow these steps:

Open the NuGet Package Manager Console. You can find it by going to View -> Other Windows -> Package Manager Console.

How to Add a Barcode in Crystal Reports using C#: Figure 3 - Open NuGet Package Manager Console. Navigate to the View menu - Other Windows - Package Manager Console

In the Package Manager Console, use the following command to install the IronBarcode library:

Install-Package BarCode

Press Enter to execute the command.

Alternatively, you can install IronBarcode library using the Manage NuGet Packages for Solution:

How to Add a Barcode in Crystal Reports using C#: Figure 4 - Install IronBarcode using the Manage NuGet Package for Solution by searching IronBarcode in the search bar of NuGet Package Manager, then select the project and click on the Install button.

Wait for the NuGet Package Manager to download and install the IronBarcode library and its dependencies. Once the installation is complete, you'll see a confirmation message in the Package Manager Console.

Now, the IronBarcode library is installed in your project, and you can start using its features for barcode generation and reading.

Generate barcode images and store them in the Database

We'll generate barcode images and store them in the database using ADO.NET. The following code demonstrates the example of generating a barcode in C#.

using System;
using System.Data.SqlClient;
using IronBarCode;

class Program
{
    static void Main(string[] args)
    {
        // Create a barcode from a string value using Code128 format.
        var myBarcode = BarcodeWriter.CreateBarcode("77446252", BarcodeWriterEncoding.Code128);
        // Add the barcode value text below the barcode image.
        myBarcode.AddBarcodeValueTextBelowBarcode();
        // Resize the barcode image.
        myBarcode.ResizeTo(600, 300);

        // SQL connection to the SQL Server database.
        using (SqlConnection cn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=ProductDB;User ID=sa;Password=123456;Integrated Security=SSPI;"))
        {
            // SQL command to insert the barcode into the Products table.
            SqlCommand cmd = new SqlCommand($"INSERT INTO dbo.Products VALUES (77446252, 'Pine Apple Small', '100', @Barcode)", cn);
            // Add parameter for the barcode binary data.
            cmd.Parameters.AddWithValue("@Barcode", myBarcode.BinaryStream);

            // Open the connection, execute the query, close the connection.
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
        }
    }
}
using System;
using System.Data.SqlClient;
using IronBarCode;

class Program
{
    static void Main(string[] args)
    {
        // Create a barcode from a string value using Code128 format.
        var myBarcode = BarcodeWriter.CreateBarcode("77446252", BarcodeWriterEncoding.Code128);
        // Add the barcode value text below the barcode image.
        myBarcode.AddBarcodeValueTextBelowBarcode();
        // Resize the barcode image.
        myBarcode.ResizeTo(600, 300);

        // SQL connection to the SQL Server database.
        using (SqlConnection cn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=ProductDB;User ID=sa;Password=123456;Integrated Security=SSPI;"))
        {
            // SQL command to insert the barcode into the Products table.
            SqlCommand cmd = new SqlCommand($"INSERT INTO dbo.Products VALUES (77446252, 'Pine Apple Small', '100', @Barcode)", cn);
            // Add parameter for the barcode binary data.
            cmd.Parameters.AddWithValue("@Barcode", myBarcode.BinaryStream);

            // Open the connection, execute the query, close the connection.
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
        }
    }
}
Imports System
Imports System.Data.SqlClient
Imports IronBarCode

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create a barcode from a string value using Code128 format.
		Dim myBarcode = BarcodeWriter.CreateBarcode("77446252", BarcodeWriterEncoding.Code128)
		' Add the barcode value text below the barcode image.
		myBarcode.AddBarcodeValueTextBelowBarcode()
		' Resize the barcode image.
		myBarcode.ResizeTo(600, 300)

		' SQL connection to the SQL Server database.
		Using cn As New SqlConnection("Data Source=localhost\SQLEXPRESS;Initial Catalog=ProductDB;User ID=sa;Password=123456;Integrated Security=SSPI;")
			' SQL command to insert the barcode into the Products table.
			Dim cmd As New SqlCommand($"INSERT INTO dbo.Products VALUES (77446252, 'Pine Apple Small', '100', @Barcode)", cn)
			' Add parameter for the barcode binary data.
			cmd.Parameters.AddWithValue("@Barcode", myBarcode.BinaryStream)

			' Open the connection, execute the query, close the connection.
			cn.Open()
			cmd.ExecuteNonQuery()
			cn.Close()
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

Code Explanation

1. Barcode Generation

  1. var myBarcode = BarcodeWriter.CreateBarcode("77446252", BarcodeWriterEncoding.Code128);

    • This line creates a barcode using the BarcodeWriter class's CreateBarcode() method. The barcode is generated from the data represented by the string "77446252" using the Code 128 encoding format. The myBarcode variable now holds the generated barcode.
  2. AddBarcodeValueTextBelowBarcode()

    • This function adds a description text of the barcode value below the barcode.
  3. ResizeTo(600, 300)

    • Adjusts the height and width of the barcode image to the provided dimensions.
  4. You can use the SaveAs() method to save barcode images in the file system.

The following barcode will be generated from the above code:

How to Add a Barcode in Crystal Reports using C#: Figure 5 - Output: Generated barcode

2. Database Connection Setup

  1. SqlConnection cn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=ProductDB;User ID=sa;Password=123456;Integrated Security=SSPI;");

    • Establishes a connection to a SQL Server database. The connection string specifies the server (localhost\\SQLEXPRESS), the initial catalog (database name: ProductDB), and the authentication credentials (user ID sa and password 123456).

3. SQL Command Creation

  1. SqlCommand cmd = new SqlCommand($"INSERT INTO dbo.Products VALUES (77446252, 'Pine Apple Small', '100', '{myBarcode.BinaryStream}' )", cn);

    • Creates a new SqlCommand object. This command represents an SQL query to insert data into the Products table.
    • The query inserts values into the table columns: 77446252, 'Pine Apple Small', '100', and the binary stream of the generated barcode (myBarcode.BinaryStream).

4. Database Interaction

  1. cn.Open();: The connection to the database is opened.
  2. cmd.ExecuteNonQuery();: The SQL query is executed, inserting the specified values into the Products table.
  3. cn.Close();: Closes the database connection to release resources.

Design Your Crystal Reports Barcode generator

Now, design the report layout, add database connections, and arrange the necessary fields. If you're new to this, follow the following steps.

  1. Open Field Explorer => Database Field => Database Expert.

    How to Add a Barcode in Crystal Reports using C#: Figure 6 - Add database connection to the report layout: Open Field Explorer - Database Field - Database Expert.

  2. Expand Create a new Connection => OLE DB(ADO) => Make New Connection.

    How to Add a Barcode in Crystal Reports using C#: Figure 7 - Expand Create a new Connection - OLE DB(ADO) - Make New Connection.

  3. Select Microsoft OLE DB Data Source for SQL Server and click Next.

    How to Add a Barcode in Crystal Reports using C#: Figure 8 - Select Microsoft OLE DB Data Source for SQL Server and click Next.

  4. Provide the Server Name, Login Credential, and Database Name as shown below.

    How to Add a Barcode in Crystal Reports using C#: Figure 9 - Specify the SQL Server Name, Login Credential, and Database Name. Then click on Next - then Finish.

  5. Press the Next button, a new window will appear, and then click Finish.
  6. Select the table you want to add. In this case, select the Products table.

    How to Add a Barcode in Crystal Reports using C#: Figure 10 - Add table: Select the Products table from the ProductDB database. Then click on the OK button.

  7. Click on the OK Button.

We have set up a Database Connection. Now, let's set up the Report layout.

Now, I have added a Text Box with the text "Barcode in Crystal report C#". I added a text box, and drag & drop the Product ID, Product Name, Product Price Field, and Product Barcode from the database fields and placed them inside the box as shown below.

How to Add a Barcode in Crystal Reports using C#: Figure 11 - Create a Crystal Report in C#. Drag and drop the Product ID, Product Name, Product Price, Product Barcode fields from database fields.

See the Crystal Report Preview in Crystal Report Viewer.

How to Add a Barcode in Crystal Reports using C#: Figure 12 - Check the Crystal Report Preview in Crystal Report Viewer.

Build and run the project. The output is as follows:

How to Add a Barcode in Crystal Reports using C#: Figure 13 - Output: Crystal Report with barcode

I have not downloaded the sample dataset package, ensuring I had the correct data file, and proceeded to create a Crystal Report in C# for comprehensive data visualization.

In this way, we can create a barcode in the Crystal Reports Application without downloading the Barcode Font. Similarly, we can also add a QR Code as per your requirement.

Conclusion

In conclusion, integrating barcodes into Crystal Reports using C# is a powerful way to enhance data representation and management. Choosing a reliable barcode library like IronBarcode streamlines the process, offering versatility and ease of use. IronBarcode, with its support for various barcode types, resizing, and customization features, proves to be a valuable asset in barcode generation and reading tasks. The step-by-step guide provided here ensures a seamless implementation process, from selecting the library to designing the Crystal Report layout.

Moreover, IronBarcode offers developers the opportunity to unlock additional functionalities and support to enhance their barcode integration experience. This flexibility makes IronBarcode a compelling choice for developers, whether they are working on small-scale projects or enterprise-level applications.

常见问题解答

如何使用 C# 将条形码集成到 Crystal Reports 中?

要使用 C# 将条形码集成到 Crystal Reports 中,可以使用 IronBarcode 生成条形码图像。首先安装 IronBarcode 库,生成条形码图像,将其保存到数据库,然后使用 Crystal Reports 设计布局并合并条形码图像。

在 C# 中生成条形码的过程是什么?

使用 IronBarcode,可以通过创建条形码对象、使用调整大小和添加文本等选项进行自定义,然后将图像保存到文件或数据库中以供报告使用来生成 C# 中的条形码。

如何在 C# 中将条形码图像保存到数据库?

使用 IronBarcode 生成条形码图像后,可以通过将图像转换为二进制格式并使用 ADO.NET 将其插入数据库表来将其保存到数据库。

在 C# 中使用 IronBarcode 进行条形码生成的好处是什么?

IronBarcode 在 C# 中生成条形码很有帮助,因为它支持各种条形码格式,允许自定义,并提供一个简单的 API 可以快速集成到应用程序中,增强库存和文档跟踪。

如何在 Crystal Reports 中设置用于条形码集成的数据库连接?

要在 Crystal Reports 中设置数据库连接,使用字段资源管理器导航到数据库字段,然后进入数据库专家,展开创建一个新连接,选择 OLE DB(ADO),并使用必要的服务器详细信息配置您的连接。

可以使用 IronBarcode 在 Crystal Reports 中生成二维码吗?

是的,IronBarcode 可以用于生成二维码以及其他条形码类型,使其成为将不同条形码格式集成到 Crystal Reports 中的多功能选择。

设计带有条形码的 Crystal Report 布局应该遵循哪些步骤?

设计带有条形码的 Crystal Report 布局涉及创建报表模板,建立数据库连接,添加条形码图像字段,并格式化报告以有效合并条形码数据。

IronBarcode 如何在 C# 项目中增强报告功能?

IronBarcode 通过提供一种简单易用的解决方案生成和集成条形码来增强 C# 项目的报告能力,从而改善报告中的数据可视化和管理。

Jordi Bardia
软件工程师
Jordi 最擅长 Python、C# 和 C++,当他不在 Iron Software 利用这些技能时,他就在游戏编程。分享产品测试、产品开发和研究的责任,Jordi 在持续的产品改进中增加了巨大的价值。多样的经验使他面临挑战并保持投入,他表示这是在 Iron Software 工作的最喜欢的方面之一。Jordi 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。