Saltar al pie de página
USO DE IRONBARCODE

Tutorial de Generador de Código de Barras .NET

Given the swift rise in barcode usage, developers must be able to generate barcodes in their preferred programming language. So, this tutorial will demonstrate how to generate barcodes in .NET.

Barcode Generator .NET Tutorial

  1. Creating a project in Visual Studio
  2. Installing the C# Barcode Generator Library
  3. Designing the UI for the Windows Forms Application
  4. Writing the code for core functionality
  5. Running the .NET barcode generator

Let's begin the tutorial.

Create the Project

This tutorial uses the latest version of Visual Studio and the Windows Forms Application template. You can use the application of your choice and use your existing project and version.

Open Visual Studio > Click on Create New Project > Select Windows Forms Application Template > Press Next > Name the Project > Press Next => Select your target .NET Framework => Click on Create Button.

Barcode Generator .NET Tutorial, Figure 1: Create a new Windows Forms Application Create a new Windows Forms Application

Installing the Barcode Library

There are many benefits to installing a barcode generator library. IronBarcode, written in C#, provides functions to create barcodes and QR codes with just a single line of code. It also supports saving the QR code or barcode in the desired file format. Furthermore, it provides free service and runtime support for generating barcodes in .NET.

Let's start with installing the IronBarcode NuGet Package. You can install it using one of the following three methods:

Package Manager Console

Write the following command in the Package Manager Console. It will download and install the package for you.

Install-Package BarCode

Barcode Generator .NET Tutorial, Figure 2: Package Manager Console installation step Package Manager Console installation step

NuGet Package Manager Solution

You can also install the Barcode Package by using the NuGet Package Solution. Simply follow these steps:

Click on Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

This will open NuGet Package Manager for you. Click on Browse and search "IronBarCode", then install the library.

Barcode Generator .NET Tutorial, Figure 3: NuGet Package Manager UI NuGet Package Manager UI

As an alternative, the IronBarCode.Dll can be downloaded and added to your project as a reference from .NET Barcode DLL.

Design the Windows Forms

The UI for the .NET Barcode generator should have 2 labels, 1 rich text box, and 1 picture box to display the generated barcode image. The image below shows a simple design for demonstration purposes.

Barcode Generator .NET Tutorial, Figure 4: Design the Windows Forms Application Design the Windows Forms Application

Write Code for Generating Barcode

Double-click the "Generate" button. The following code will appear:

private void button1_Click(object sender, EventArgs e)
{
    // This function will be triggered when the "Generate" button is clicked
}
private void button1_Click(object sender, EventArgs e)
{
    // This function will be triggered when the "Generate" button is clicked
}
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
	' This function will be triggered when the "Generate" button is clicked
End Sub
$vbLabelText   $csharpLabel

Add the following namespaces at the top of your code file:

using IronBarCode; // Import the IronBarCode library to handle barcode operations
using System.Drawing; // Import for image manipulation
using System.Windows.Forms; // Import for Windows Forms functionality
using IronBarCode; // Import the IronBarCode library to handle barcode operations
using System.Drawing; // Import for image manipulation
using System.Windows.Forms; // Import for Windows Forms functionality
Imports IronBarCode ' Import the IronBarCode library to handle barcode operations
Imports System.Drawing ' Import for image manipulation
Imports System.Windows.Forms ' Import for Windows Forms functionality
$vbLabelText   $csharpLabel

Write the following code inside the button1_Click() function:

// Generate a barcode with the specified value and encoding
GeneratedBarcode MyBarCode = IronBarCode.BarcodeWriter.CreateBarcode(BarcodeValue.Text, BarcodeWriterEncoding.Code128);

// Save the generated barcode as a PNG file
MyBarCode.SaveAsPng("MyBarCode.png");

// Display the generated barcode image in the PictureBox
BarcodeImage.Image = new Bitmap("MyBarCode.png");
// Generate a barcode with the specified value and encoding
GeneratedBarcode MyBarCode = IronBarCode.BarcodeWriter.CreateBarcode(BarcodeValue.Text, BarcodeWriterEncoding.Code128);

// Save the generated barcode as a PNG file
MyBarCode.SaveAsPng("MyBarCode.png");

// Display the generated barcode image in the PictureBox
BarcodeImage.Image = new Bitmap("MyBarCode.png");
' Generate a barcode with the specified value and encoding
Dim MyBarCode As GeneratedBarcode = IronBarCode.BarcodeWriter.CreateBarcode(BarcodeValue.Text, BarcodeWriterEncoding.Code128)

' Save the generated barcode as a PNG file
MyBarCode.SaveAsPng("MyBarCode.png")

' Display the generated barcode image in the PictureBox
BarcodeImage.Image = New Bitmap("MyBarCode.png")
$vbLabelText   $csharpLabel

Let's understand the code, line by line:

  • GeneratedBarcode is a data type that represents the generated barcode.

  • CreateBarcode is the function from the BarcodeWriter class in the IronBarCode package, used to generate the barcode based on user input.

  • BarcodeValue.Text retrieves the text entered by the user, which will be encoded into the barcode.

  • BarcodeWriterEncoding.Code128 specifies the encoding scheme for generating the barcode. You can change this to other encoding types like BarcodeWriterEncoding.QRCode for generating QR codes.

  • SaveAsPng("MyBarCode.png") saves the barcode image as a PNG file.

  • BarcodeImage is a PictureBox control on the form used to display the barcode image to the user.

Run the .NET Barcode Generator

Press Ctrl + F5 to run the application.

Barcode Generator .NET Tutorial, Figure 5: Run the Barcode generator application Run the Barcode generator application

Write the value inside the text box that you want to encode in the barcode as shown below.

Barcode Generator .NET Tutorial, Figure 6: Paste the URL to generate a barcode Paste the URL to generate a barcode

Now, click the "Generate" button. The barcode will be generated as shown below.

Barcode Generator .NET Tutorial, Figure 7: Generated barcode in the Windows Forms Application Generated barcode in the Windows Forms Application

Display the Value of the Barcode

Next, you can display the value of the barcode with a single line of code:

// Add the encoded barcode value as text below the barcode image
MyBarCode.AddBarcodeValueTextBelowBarcode();
// Add the encoded barcode value as text below the barcode image
MyBarCode.AddBarcodeValueTextBelowBarcode();
' Add the encoded barcode value as text below the barcode image
MyBarCode.AddBarcodeValueTextBelowBarcode()
$vbLabelText   $csharpLabel

Output

Barcode Generator .NET Tutorial, Figure 8: Generate a barcode from a string value Generate a barcode from a string value

Summary

IronBarcode features a friendly API for developers to read and write barcodes for .NET, optimizing accuracy and ensuring a low error rate in real-world software. Visit the official documentation page for more information about IronBarcode.

Currently, if you buy the complete Iron Suite, you can get five libraries for the price of two. For more information.

Preguntas Frecuentes

¿Cómo puedo generar códigos de barras en .NET?

Puedes generar códigos de barras en .NET usando la biblioteca IronBarcode creando un proyecto en Visual Studio, instalando la biblioteca, diseñando la UI y escribiendo código para generar y mostrar el código de barras.

¿Cuáles son los métodos de instalación para la biblioteca de código de barras?

Puedes instalar la biblioteca IronBarcode usando el Administrador de Consola de Paquetes, la Solución del Administrador de Paquetes NuGet, o descargando directamente el DLL y añadiéndolo a tu proyecto.

¿Qué elementos de la UI son esenciales para una aplicación generadora de códigos de barras?

Los elementos esenciales de la UI para una aplicación generadora de códigos de barras incluyen dos etiquetas, un cuadro de texto enriquecido para la entrada y un cuadro de imagen para mostrar la imagen del código de barras generado.

¿Qué pasos están involucrados en la codificación de la función de generación de códigos de barras?

Para codificar la función de generación de códigos de barras, escribe código en la función button1_Click para generar un código de barras usando IronBarcode, guardarlo como PNG y mostrarlo en el PictureBox.

¿Qué tipos de códigos de barras pueden generarse usando esta biblioteca?

IronBarcode soporta la generación de varios tipos de códigos de barras, incluyendo Code128 y QRCode, entre otros.

¿Cómo puedo añadir texto debajo del código de barras generado?

Puedes añadir el valor codificado del código de barras como texto debajo de la imagen usando el método AddBarcodeValueTextBelowBarcode en la biblioteca IronBarcode.

¿Qué ventajas ofrece el uso de la biblioteca IronBarcode?

El uso de IronBarcode ofrece una generación de códigos de barras optimizada con alto rendimiento y precisión, una API fácil de usar, y bajas tasas de error en aplicaciones del mundo real.

¿Dónde puedo acceder a documentación detallada para la biblioteca de códigos de barras?

Documentación detallada y ejemplos para la biblioteca IronBarcode se pueden encontrar en el sitio web oficial de IronBarcode.

¿Hay promociones actuales para la biblioteca de códigos de barras?

Sí, hay una promoción donde comprar el paquete completo Iron Suite te permite recibir cinco bibliotecas por el precio de dos.

¿Cómo puedo solucionar problemas comunes con la generación de códigos de barras en .NET?

Los problemas comunes a menudo se pueden resolver asegurando la correcta instalación de la biblioteca IronBarcode, verificando que los componentes de la UI estén correctamente configurados y verificando que el código de generación de códigos de barras esté libre de errores.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más