Implementing a Custom DataGridViewBarcodeCell

Barcodes are not only used in documents or forms. A typical application is the display of a specific cell value as a barcode in a DataGridView. This sample shows how to use TX Barcode .NET to implement a custom DataGridViewBarcodeCell.

The source code is contained in the following directories:

  • Samples\WinForms\CSharp\DataGridViewBarcode
  • Samples\WinForms\VB.NET\DataGridViewBarcode

A DataGridView cell has two modes: An edit mode that is used when the user types in the value for the cell and a display mode that shows an image representation of the barcode.

Open the sample project in Visual Studio and start the application. A form with a DataGridView is shown. The column Barcode column shows barcode images.


Use the mouse and click into one of the shown barcodes to select the cell. Click again to activate the edit mode of the custom cell. A text box is used as the editor in this case. Change the value to another numeric value such as "12345" and press return.


The barcode is updated, the custom cell switches to the display mode and shows the updated image representation.


In order to create the image representation, TX Barcode .NET provides a method that paints the actual barcode into a Graphics object. The following code shows how to use this method:

Bitmap bmp = new Bitmap(cellSize.Width, cellSize.Height);
ctl.BackColor = DataGridView.DefaultCellStyle.SelectionBackColor;
ctl.ForeColor = DataGridView.DefaultCellStyle.SelectionForeColor;

Graphics g = Graphics.FromImage(bmp);
ctl.PrintPaint(g, new Rectangle(0, 0, bmp.Width, bmp.Height));