# Bunifu Datagrid View

## Overview

**Bunifu Datagrid View** is a feature-rich .NET valuable control for displaying data in a tabular format. It comes with beautiful in-built themes and a vast range of functions: data binding, editing, adding, custom sorting, selecting, and support for PDF formats.

![](https://downloads.intercomcdn.com/i/o/102035360/6e54737741fcb8f441949121/bunifu-datagridview-sample-05.png)

## **Getting Started**

This section provides a quick overview of working with the tabular data for WinForms. We shall walk through the entire process of creating a real-world data grid.

### Adding `BunifuDatagridView` at Design Time

It's easy to add `BunifuDatagridView` control at design time. Start by locating `BunifuDatagridView` from your toolbox and drag it to your form as shown below. Then customize it to your desired look and feel using properties elaborated on later in this documentation.

&#x20;

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-Me4aj1G9JDwr8AVqIc9%2F-Me4hW-YndtWqKWWmuI7%2Fdt03.gif?alt=media\&token=800c8e40-1f26-428c-ae09-102b8de1d770)

### Adding `BunifuDataGridView` at Run Time

`BunifuDataGridView` works for both **C#** and **VB.NET**. We will use the Form’s Load event to write our sample code to create a BunifuDatagridView and populate the table with **built-in sample data**.

{% tabs %}
{% tab title="C#" %}

```csharp
using System;
using Bunifu.UI.WinForms;
using System.Drawing;
using System.Windows.Forms;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            BunifuDataGridView bunifuDataGridView = new BunifuDataGridView();
            bunifuDataGridView.Size = new Size(600, 250);
            bunifuDataGridView.Location = new Point(12, 28);
            this.Controls.Add(bunifuDataGridView);
            bunifuDataGridView.PopulateWithSampleData();
        }
    }
}

```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Imports System
Imports Bunifu.UI.WinForms
Imports System.Drawing
Imports System.Windows.Forms

Namespace BunifuGrid
	Partial Public Class Form1
		Inherits Form

		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
			Dim bunifuDataGridView As New BunifuDataGridView()
			bunifuDataGridView.Size = New Size(600, 250)
			bunifuDataGridView.Location = New Point(12, 28)
			Me.Controls.Add(bunifuDataGridView)
			bunifuDataGridView.PopulateWithSampleData()
		End Sub
	End Class
End Namespace

```

{% endtab %}
{% endtabs %}

Here's the output for the above code:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-Me4qqNx3kBgVQ8cydq1%2F-Me4r1F3gKXDIfFb1Q0v%2Fdt04.gif?alt=media\&token=d56eafae-18a9-4cef-98c7-ddd5d10ed49c)

### Creating a simple data entry application (No code!)

**Step 1:** Create the following form below with the following controls as shown on the labels.&#x20;

{% hint style="info" %}
For the DataGridView set the **`backgroundColor`** property to a color value of **white**.
{% endhint %}

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-Me9wupvFivZY9xa7T6v%2F-MeBhzZPX0KDBTgXG-44%2Fimg06.jpg?alt=media\&token=659ed4ce-a1bc-4065-839a-284d938551c6)

**Step two:** Create columns on the Datagrid. Here's how to do it in the design view:

|                                                                                                                                              |   |
| -------------------------------------------------------------------------------------------------------------------------------------------- | - |
| a) Select the Datagrid and click on the glyph play icon ( :arrow\_forward: ) at the top right position in order to open the ***Smart Tag.*** |   |
| b) Click on the Add Column link which opens a dialog that displays **Column Collection Editor**                                              |   |
| c) Add the following columns as shown below                                                                                                  |   |

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-Me9wupvFivZY9xa7T6v%2F-MeBn0XlV-iy6p4p72vl%2Fimage.png?alt=media\&token=4cb3f39c-3547-4510-a7ef-955a6d44187f)

d) Now, run the application, the below output will occur

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-Me9wupvFivZY9xa7T6v%2F-MeBueSZ7zq03MZ_1qri%2Fdt05.gif?alt=media\&token=0ca5fb6e-9d0f-49bf-a22f-345f0c8aa8b2)

{% hint style="success" %}
Let's take a deep dive and get insights into the properties that are available on Bunifu DataGrid View.
{% endhint %}

## Appearance

Bunifu DataGrid View allows you to customize the appearance of your tabular data with ease. Here are the features that you can customize:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MhYltYQgiCaKUXGJYeW%2F-MhYmNlLjAqCoQhedC4r%2Fimage.png?alt=media\&token=c301696c-2156-413a-af62-e1da8715c3ce)

### 1. Built-In Themes

`BunifuDataGridView` offers 16+ different types of themes that you may utilize in your application. The **`Theme`** property allows you to get the property's value or set an enumerated theme value for your tabular data.

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MeFgl3GG6LaPoZjTTuQ%2F-MeLegX39DVLo_lHEyAm%2Fdt08.gif?alt=media\&token=9a694e87-fa2f-4eb5-b39e-a2e2f13697d2)

`BunifuDataGridView` exposes an array of properties that can be used to customize the theme. The following is a sampling of the properties related to our chosen theme:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MeWN-ZVox8TX2c4WMof%2F-MeWPJDPCdJYvH7_bXUG%2Fimage.png?alt=media\&token=51222a1b-bbfc-4e85-8787-0996b7255ad6)

{% hint style="info" %}
In some cases, you may need to change some of the property values in your current theme. The **`AllowCustomTheming`** property allows you to get the property's boolean value or set a boolean value that, when set to true, will enable you to edit the property values that were used to design the theme you selected.
{% endhint %}

| Property       | Description                                                                                                                      |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `CurrentTheme` | This property contains an array of properties that allows you to get or set the design attributes of the theme chosen with ease. |

{% hint style="success" %}
Let's take a deep dive to the **`CurrentTheme`** properties&#x20;
{% endhint %}

#### a) `GridColor`

This property allows you to get or set a color value that will be applied on the grid lines separating the cells. It supports the use of RGB and HEX color values.

#### b) `AlternatingRows`

This property contains an array of properties that allow you to get or set the design attributes and styles associated with the **odd rows**.

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MeWPZ_G0RpRFBHER91A%2F-MeXnBKpz9q-sm3PgKEl%2Fimage.png?alt=media\&token=7c41c00f-eedb-4fb9-a240-ee00b0388f57)

| Property           | Description                                                                                                                                                                           |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `BackColor`        | This property allows you to get or set the background color for each cell associated with odd rows. It supports the use of both RGB and HEX color values.                             |
| `Font`             | This property allows you to get or set the font style for each cell's text in odd rows.                                                                                               |
| `ForeColor`        | This property allows you to get or set the text color for each cell in an odd row.                                                                                                    |
| SelectionBackColor | This property allows you to get or set the background color for each odd row cell, which gets applied when the row is selected. It supports the use of both RGB and HEX color values. |
| SelectionForeColor | This property allows you to get or set the text color for each odd row cell, which gets applied when the row is selected.  It supports the use of both RGB and HEX color values.      |

{% tabs %}
{% tab title="C#" %}

```csharp
//set back color to the alternate row
bunifuDataGridView1.CurrentTheme.AlternatingRowsStyle.BackColor = Color.FromArgb(199, 226, 199);
//set text color to cells in the alternate row
bunifuDataGridView1.CurrentTheme.AlternatingRowsStyle.ForeColor = Color.Black;
//apply selection text color to cells im the alternate row
bunifuDataGridView1.CurrentTheme.AlternatingRowsStyle.SelectionForeColor = Color.White;
//set selection background color to the cells in the alternate row
bunifuDataGridView1.CurrentTheme.AlternatingRowsStyle.SelectionBackColor = Color.FromArgb(122, 185, 122);
//apply a font style to the cell's text in the alternate rows
bunifuDataGridView1.CurrentTheme.AlternatingRowsStyle.Font = new Font("Segoe UI", 10,FontStyle.Regular);
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
'Apply back color to the alternate row
bunifuDataGridView1.CurrentTheme.AlternatingRowsStyle.BackColor = Color.FromArgb(199, 226, 199)
'Apply text color to cells in the alternate row
bunifuDataGridView1.CurrentTheme.AlternatingRowsStyle.ForeColor = Color.Black
'Apply selection text color to cells im the alternate row
bunifuDataGridView1.CurrentTheme.AlternatingRowsStyle.SelectionForeColor = Color.White
'Apply selection background color to the cells in the alternate row
bunifuDataGridView1.CurrentTheme.AlternatingRowsStyle.SelectionBackColor = Color.FromArgb(122, 185, 122)
'Apply a font style to the cell's text in the alternate rows
bunifuDataGridView1.CurrentTheme.AlternatingRowsStyle.Font = New Font("Segoe UI", 10,FontStyle.Regular)

```

{% endtab %}
{% endtabs %}

#### c) `RowsStyle`

This property contains an array of properties that allow you to get or set the design attributes and cell styles associated with a **non-odd row** in the data grid.

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MeYvm9nc7n2WWbeFJ-w%2F-MeZ1K5w7OOf1GRTtqHI%2Fimage.png?alt=media\&token=fdfef1eb-7fdd-4572-a557-ceca4718df64)

Below is a description of the properties that you can modify in the `RowsStyle` prop:&#x20;

| Property           | Description                                                                                                                                                                               |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `BackColor`        | This property allows you to get or set the background color for each cell of non-odd rows. It supports the use of both RGB and HEX color values.                                          |
| `Font`             | This property allows you to get or set the font style for each cell's text in non-odd rows.                                                                                               |
| `ForeColor`        | This property allows you to get or set the text color for each cell's text in non-odd rows.                                                                                               |
| SelectionBackColor | This property allows you to get or set the background color for each non-odd row cell, which gets applied when the row is selected. It supports the use of both RGB and HEX color values. |
| SelectionForeColor | This property allows you to get or set the text color for each non-odd row cell, which gets applied when the row is selected.  It supports the use of both RGB and HEX color values.      |

{% tabs %}
{% tab title="C#" %}

```csharp
//apply back color to the row
bunifuDataGridView1.CurrentTheme.RowsStyle.BackColor = Color.FromArgb(210, 231, 210);
//apply text color to cells in the row
bunifuDataGridView1.CurrentTheme.RowsStyle.ForeColor = Color.Black;
//set selection text color to cells in the row
bunifuDataGridView1.CurrentTheme.RowsStyle.SelectionForeColor = Color.White;
//set selection background color to the cells in the row
bunifuDataGridView1.CurrentTheme.RowsStyle.SelectionBackColor = Color.FromArgb(122, 185, 122);
//apply a font style to the cell's text in the row
bunifuDataGridView1.CurrentTheme.RowsStyle.Font = new Font("Segoe UI", 10, FontStyle.Regular);
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
'Apply back color to the row
bunifuDataGridView1.CurrentTheme.RowsStyle.BackColor = Color.FromArgb(210, 231, 210)
'Apply text color to cells in the row
bunifuDataGridView1.CurrentTheme.RowsStyle.ForeColor = Color.Black
'Apply selection text color to cells in the row
bunifuDataGridView1.CurrentTheme.RowsStyle.SelectionForeColor = Color.White
'Apply selection background color to the cells in the row
bunifuDataGridView1.CurrentTheme.RowsStyle.SelectionBackColor = Color.FromArgb(122, 185, 122)
'Apply a font style to the cell's text in the row
bunifuDataGridView1.CurrentTheme.RowsStyle.Font = New Font("Segoe UI", 10, FontStyle.Regular)

```

{% endtab %}
{% endtabs %}

#### d) `HeaderStyle`

This property contains an array of properties that allow you to get or set the design attributes and styles associated with the **column headers**.

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MeYBL9qy-vKKcijmzQr%2F-MeYCk7AS3fY_vU7L7qE%2Fimage.png?alt=media\&token=06f0bae2-c0d5-471d-9527-aa16f962aa60)

Below is a description of the properties that you can modify in the `HeaderStyle` prop:

| Property             | Description                                                                                                                                                                                         |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `BackColor`          | This property allows you to get or set the background color of each column header cell. It supports the use of both RGB and HEX color values.                                                       |
| `Font`               | This property allows you to get or set the font style of the text in the column header cells.                                                                                                       |
| `ForeColor`          | This property allows you to get or set the color for the text in each column header cells.                                                                                                          |
| `SelectionBackColor` | This property allows you to get or set the background color of the column's header cell, which will be applied when the column is selected. It supports the use of both RGB and HEX color values.   |
| `SelectionForeColor` | This property allows you to get or set the color of text content in a column header cell, which will be applied when the column is selected.  It supports the use of both RGB and HEX color values. |

{% tabs %}
{% tab title="C#" %}

```csharp
//apply back color to the column header
bunifuDataGridView1.CurrentTheme.HeaderStyle.BackColor = Color.ForestGreen;
//set text color to cells in the column header
bunifuDataGridView1.CurrentTheme.HeaderStyle.ForeColor = Color.White;
//set selection text color to cells in the column header
bunifuDataGridView1.CurrentTheme.HeaderStyle.SelectionForeColor = Color.White;
//apply selection background color to the cells in the column
bunifuDataGridView1.CurrentTheme.HeaderStyle.SelectionBackColor = Color.FromArgb(27, 111, 27);
//set a font style to the cell's text in the column header
bunifuDataGridView1.CurrentTheme.HeaderStyle.Font = new Font("Segoe UI", 10, FontStyle.Regular);
//set the column header height
bunifuDataGridView1.ColumnHeadersHeight = 36;
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
'apply back color to the column header
bunifuDataGridView1.CurrentTheme.HeaderStyle.BackColor = Color.ForestGreen
'set text color to cells in the column header
bunifuDataGridView1.CurrentTheme.HeaderStyle.ForeColor = Color.White
'set selection text color to cells in the column header
bunifuDataGridView1.CurrentTheme.HeaderStyle.SelectionForeColor = Color.White
'apply selection background color to the cells in the column
bunifuDataGridView1.CurrentTheme.HeaderStyle.SelectionBackColor = Color.FromArgb(27, 111, 27)
'set a font style to the cell's text in the column header
bunifuDataGridView1.CurrentTheme.HeaderStyle.Font = New Font("Segoe UI", 10, FontStyle.Regular)
'set the column header height
bunifuDataGridView1.ColumnHeadersHeight = 36

```

{% endtab %}
{% endtabs %}

### 2. Column properties

`BunifuDataGridView` provides you support for creating and editing both bound and unbound columns with ease. The Below section shows the various properties you can work with to design your column appearance and behavior.

| Property name | Description                                                                                                                                                       |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Columns       | This property allows you to get the current collection of columns or set a column collection object containing an array of unbound columns for your tabular data. |

The column collection editor is provided in the design view, and it allows you to view, add, update, and delete the existing columns. The columns to be added can be chosen from built-in column types or your own column.

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MeMaR4Q_sMt2-KYMvXi%2F-MeOjPRuKIVynKCWMfAK%2Fimage.png?alt=media\&token=597757a5-499a-42e5-a6d3-8eb0d6c08f9e)

Like the standard DataGridView, the created the unbound column gives you further ability to edit its properties. See [how](https://docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/using-the-designer-with-the-windows-forms-datagridview-control?view=netframeworkdesktop-4.8) to get more insights on editing the properties provided in the column.

You also can add or edit different types of columns(e.g., Textbox columns, image view columns, e.t.c) using any language you prefer to code with( i.e., the **C#** and **VB.NET** languages).&#x20;

Here's how you can add textbox columns through code:

{% tabs %}
{% tab title="C#" %}

```csharp
private void Form1_Load(object sender, EventArgs e)
{
    bunifuDataGridView1.Columns.AddRange(
    new DataGridViewTextBoxColumn()
    {
        HeaderText = "Product ID",
        Name = "productIDColumn"
    },
    new DataGridViewTextBoxColumn()
    {
        HeaderText = "Product Name",
        Name = "productNameColumn"
    },
    new DataGridViewTextBoxColumn()
    {
        HeaderText = "Customer Name",
        Name = "customerNameColumn"
    },
    new DataGridViewTextBoxColumn()
    {
        HeaderText = "Country",
        Name = "countryColumn"
    },
    new DataGridViewTextBoxColumn()
    {
        HeaderText = "Shipping City",
        Name = "shippingCityColumn"
    }
    );
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
	bunifuDataGridView1.Columns.AddRange(New DataGridViewTextBoxColumn() With {
		.HeaderText = "Product ID",
		.Name = "productIDColumn"
	}, New DataGridViewTextBoxColumn() With {
		.HeaderText = "Product Name",
		.Name = "productNameColumn"
	}, New DataGridViewTextBoxColumn() With {
		.HeaderText = "Customer Name",
		.Name = "customerNameColumn"
	}, New DataGridViewTextBoxColumn() With {
		.HeaderText = "Country",
		.Name = "countryColumn"
	}, New DataGridViewTextBoxColumn() With {
		.HeaderText = "Shipping City",
		.Name = "shippingCityColumn"
	})
End Sub

```

{% endtab %}
{% endtabs %}

On running the code above, the below output will occur:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MeOpZEHnzTo3baN20Up%2F-MeOuYPf-arfyxSNkoYf%2Fimage.png?alt=media\&token=ae26ced2-ef00-439f-8f6e-4adb42a6a512)

{% hint style="info" %}
Alternatively,  `BunifuDataGridView` can be bound to a data source, where the columns will be generated automatically. This will be discussed in further detail, later in this documentation.
{% endhint %}

The columns can be accessed through its column index or using its `Name` property from the `bunifuDataGrid.Columns` collection.

{% tabs %}
{% tab title="C#" %}

```csharp
DataGridViewColumn dataGridViewColumn = bunifuDataGridView1.Columns[0];
//or
DataGridViewColumn gridViewColumn = bunifuDataGridView1.Columns["productIDColumn"];
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Dim dataGridViewColumn As DataGridViewColumn = bunifuDataGridView1.Columns(0)
'or
Dim gridViewColumn As DataGridViewColumn = bunifuDataGridView1.Columns("productIDColumn")

```

{% endtab %}
{% endtabs %}

A column can be removed using the Remove and RemoveAt methods. The Clear method removes all columns from bunifuDataGrid.Columns collection.

{% tabs %}
{% tab title="C#" %}

```csharp
//remove the second column
bunifuDataGridView1.Columns.RemoveAt(1);
//or
bunifuDataGridView1.Columns.Remove(gridViewColumn);
//clear all columns
bunifuDataGridView1.Columns.Clear();
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
'remove the second column
bunifuDataGridView1.Columns.RemoveAt(1)
'or
bunifuDataGridView1.Columns.Remove(gridViewColumn)
'clear all columns
bunifuDataGridView1.Columns.Clear()

```

{% endtab %}
{% endtabs %}

| Property name                   | Description                                                                                                                                                                                                 |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ColumnHeadersDefaultCellStyle` | This property allows you to get the style object applied in the columns or set a cell style object that contains an array of cell style properties that can change the appearance of the column header row. |

Here are the properties that you can edit to the preferred style of your column header row.:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MeOvL5zy9Jm-aRgkO4K%2F-MeR-ofmMPFrFGIHacPu%2Fimage.png?alt=media\&token=83ea2ce6-5a30-4480-991c-bf56e3f7560b)

{% hint style="info" %}
To ensure that the properties are working at runtime, ensure the `AllowCustomTheming` prop is set to **true**.
{% endhint %}

| `Property`                    | Description                                                                                                                                                                                       |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ColumnHeadersHeightSizeMode` | This property allows you to get or set the behavior of adjusting the column headers' height during runtime.  You can specify the following values: EnableResizing, DisableResizing, and AutoSize. |
| `ColumnHeadersHeight`         | This property allows you to get or set an integer value that will resize the column header.                                                                                                       |
| `ColumnHeadersBorderStyle`    | This property allows you to get or set the border style applied to the column header.                                                                                                             |
| `ColumnHeadersVisible`        | This property allows you to get or set a boolean value that will hide the column header row when set to false. The default value is **true.**                                                     |

### 3. Row properties

BunifuDataGridView enables you to add, populate, edit or remove rows for both bound and unbound data. Here are the properties you can use to design your rows, populate and edit your rows with ease:

#### Populating your rows:

It is very easy to populate rows with an unbound data with bunifuDataGridView\.Rows collection property.

{% hint style="info" %}
Rows are only populated at runtime. Also, note that to add the rows, you must have the columns in the first place.
{% endhint %}

Here's how you can add and populate a row in `BunifuDataGridView` using C# or VB.NET language. This example assumes that you have added 5 DataGridViewTextBoxColumn instances to `BunifuDataGridView` control's column collection.

#### Steps to create the unbound data:

**Step one**: Create the following class with the get and set properties:

{% tabs %}
{% tab title="C#" %}

```csharp
class Order
{
    public string ProductId { get; set; }
    public string ProductName { get; set; }
    public string CustomerName { get; set; }
    public string Country { get; set; }
    public string ShippingCity{ get; set; }
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Friend Class Order
	Public Property ProductId() As String
	Public Property ProductName() As String
	Public Property CustomerName() As String
	Public Property Country() As String
	Public Property ShippingCity() As String
End Class

```

{% endtab %}
{% endtabs %}

**Step two**: In your Form's `Load` event write the following code:

{% tabs %}
{% tab title="C#" %}

```csharp
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Example2
{
private void Form1_Load(object sender, EventArgs e)
{
	List<Order> orderList = new List<Order>()
	{
		new Order()
		{
			ProductId = "#01293",
			ProductName = "HP Envy x360",
			CustomerName = "Dylan Gray",
			Country = "Portugal",
			ShippingCity = "Spain"
		},
		new Order()
		{
			ProductId = "#01294",
			ProductName = "Seagate SSDs",
			CustomerName = "Sarah Banks",
			Country = "United States",
			ShippingCity = "New York"
		},
		new Order()
		{
			ProductId = "#01295",
			ProductName = "HP Envy x360",
			CustomerName = "Tracy Rivera",
			Country = "Kenya",
			ShippingCity = "Nairobi"
		}
	};
foreach (var order in orderList)
{
	bunifuDataGridView1.Rows.Add(order.ProductId,order.ProductName,order.CustomerName,order.Country,order.ShippingCity);
}
}
}

```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Option Infer On

Imports System
Imports System.Collections.Generic
Imports System.Windows.Forms
Namespace Example2
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
	Dim orderList As New List(Of Order)() From {
		New Order() With {
			.ProductId="#01293",
			.ProductName="HP Envy x360",
			.CustomerName="Dylan Gray",
			.Country="Portugal",
			.ShippingCity="Spain"
		},
		New Order() With {
			.ProductId="#01294",
			.ProductName="Seagate SSDs",
			.CustomerName="Sarah Banks",
			.Country="United States",
			.ShippingCity="New York"
		},
		New Order() With {
			.ProductId="#01295",
			.ProductName="HP Envy x360",
			.CustomerName="Tracy Rivera",
			.Country="Kenya",
			.ShippingCity="Nairobi"
		}
	}
For Each order In orderList
	bunifuDataGridView1.Rows.Add(order.ProductId,order.ProductName,order.CustomerName,order.Country,order.ShippingCity)
Next order
End Sub
End Namespace

```

{% endtab %}
{% endtabs %}

Now, after running your application with the codes above, the following output will occur:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MeRKq_LNTxUdEPMgq6j%2F-MeUkH9on8wTG9I9X17s%2Fimage.png?alt=media\&token=400d0aa5-1afc-405b-bb39-d6df7227502f)

&#x20;You can also use the Rows collection to modify the values in the control or to remove rows. The following example shows you how to modify cell values programmatically.&#x20;

{% tabs %}
{% tab title="C#" %}

```csharp
//Modify the value in the second cell of the third row.
bunifuDataGridView1.Rows[2].Cells[1].Value = "Dell AlienWare M17 R4";
// The previous line is equivalent to the following line.  
bunifuDataGridView1[1,2].Value= "Dell AlienWare M17 R4";
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
'Modify the value in the second cell of the third row.
bunifuDataGridView1.Rows(2).Cells(1).Value = "Dell AlienWare M17 R4"
' The previous line is equivalent to the following line.  
bunifuDataGridView1(1,2).Value= "Dell AlienWare M17 R4"

```

{% endtab %}
{% endtabs %}

#### Styling a row cell

The appearance of a `BunifuDataGrid` cell can be customized using the `bunifuDataGridView.Rows` collection **`Style`** property. We have the option to style the back color, its selection color, the font, its forecolor, and the alignment of text in a particular cell.

The following example shows you how to style the appearance of a cell back color programmatically. The assumption is that you already have some data in your table.

{% tabs %}
{% tab title="C#" %}

```csharp
for(int i = 0; i < bunifuDataGridView1.Rows.Count; i++)
{
    //Modify the backcolor, the fore color and selection color in every cell of the FIRST column
    bunifuDataGridView1[1, i].Style.BackColor = Color.FromArgb(152, 175, 92);
    bunifuDataGridView1[1, i].Style.ForeColor = Color.White;
    bunifuDataGridView1[1, i].Style.SelectionBackColor = Color.FromArgb(63, 137, 90);
    //Modify the backcolor, the fore color and selection color every cell of the THIRD column
    bunifuDataGridView1[4, i].Style.BackColor = Color.FromArgb(152, 175, 92);
    bunifuDataGridView1[4, i].Style.ForeColor = Color.White;
    bunifuDataGridView1[4, i].Style.SelectionBackColor = Color.FromArgb(63, 137, 90);
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
For i As Integer = 0 To bunifuDataGridView1.Rows.Count - 1
	'Modify the backcolor, the fore color and selection color in every cell of the FIRST column
	bunifuDataGridView1(1, i).Style.BackColor = Color.FromArgb(152, 175, 92)
	bunifuDataGridView1(1, i).Style.ForeColor = Color.White
	bunifuDataGridView1(1, i).Style.SelectionBackColor = Color.FromArgb(63, 137, 90)
	'Modify the backcolor, the fore color and selection color every cell of the THIRD column
	bunifuDataGridView1(4, i).Style.BackColor = Color.FromArgb(152, 175, 92)
	bunifuDataGridView1(4, i).Style.ForeColor = Color.White
	bunifuDataGridView1(4, i).Style.SelectionBackColor = Color.FromArgb(63, 137, 90)
Next i

```

{% endtab %}
{% endtabs %}

The above code will output the occurrence below:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MeVTjRs_71fFYjheSAV%2F-MeWM7_qaOlgegt-X950%2Fdt09.gif?alt=media\&token=04b09951-20fe-43b9-b8c8-0fca8ece886f)

### 4. Selection

`BunifuDataGrid` enables you to select a single row or cell or multiple rows or cells. Sometimes you want your application to perform actions such as printing out the selected rows or columns based on user selections within the tabular control. Depending on the actions, you may want to restrict the kinds of selection that are possible. &#x20;

This section will explain the types of selection available for GridControl and its usability.

#### a) Row selection

You can specify a full row type of selection by setting the `BunifuDataGridView.SelectionMode` property to **`FullRowSelect.`**

When a cell or row header is clicked in the DataGrid, an entire row selection is created.

{% hint style="info" %}
By default, users can select multiple rows, columns, or cells by dragging with the mouse, pressing `CTRL` or `SHIFT` keys while selecting to extend or modify a selection. To prevent this behavior set the **`MultiSelect`** property to **false**.
{% endhint %}

To retrieve the selected values in a row, refer to the following code:

{% tabs %}
{% tab title="C#" %}

```csharp
private void bunifuButton1_Click(object sender, EventArgs e)
{
    //get the number of the selected rows
    int selectedRows = bunifuDataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);
           
    if (selectedRows > 0)
    {
        StringBuilder cellValuesStringBuilder = new StringBuilder();
        //loop through each of the selected row
        for(int i = 0; i < selectedRows; i++)
        {
            //loop the cells of a row, get their values and append them in a string builder
            for (int j = 0; j < bunifuDataGridView1.ColumnCount; j++)
            {
                cellValuesStringBuilder.Append(bunifuDataGridView1.SelectedRows[i].Cells[j].Value+"\t");
            }
            //create a new line for the next row loop
            cellValuesStringBuilder.Append("\n");
        }
        //print the output on a console
        Console.WriteLine(cellValuesStringBuilder);
    }
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Private Sub bunifuButton1_Click(ByVal sender As Object, ByVal e As EventArgs)
	'get the number of the selected rows
	Dim selectedRows As Integer = bunifuDataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)

	If selectedRows > 0 Then
		Dim cellValuesStringBuilder As New StringBuilder()
		'loop through each of the selected row
		For i As Integer = 0 To selectedRows - 1
			'loop the cells of a row, get their values and append them in a string builder
			For j As Integer = 0 To bunifuDataGridView1.ColumnCount - 1
				cellValuesStringBuilder.Append(bunifuDataGridView1.SelectedRows(i).Cells(j).Value & vbTab)
			Next j
			'create a new line for the next row loop
			cellValuesStringBuilder.Append(vbLf)
		Next i
		'print the output on a console
		Console.WriteLine(cellValuesStringBuilder)
	End If
End Sub

```

{% endtab %}
{% endtabs %}

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MeaRswUR8wBKxrRdI-W%2F-MebDMQrLiW63tzBwepV%2Fimage.png?alt=media\&token=5fd51edb-e3ee-4219-b9ba-477fd0823779)

The selected values are printed in the output screen as follows:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MeaRswUR8wBKxrRdI-W%2F-MebSsZANcIrMI0DUKeH%2Fimage.png?alt=media\&token=1c4e02bf-8836-45cc-ab52-93707820ab26)

#### b) Cell selection

A cell selection is specified by setting `BunifuDataGridView`.Selection property to **`CellSelect`**. When a user clicks on a cell, a selection is created on that cell.

The following image shows for multiple mode cell selection:

Here's a code that retrieves the selected cell values:

{% tabs %}
{% tab title="C#" %}

```csharp
private void bunifuButton1_Click(object sender, EventArgs e){
//get the number of selected cells
int selectedCells = bunifuDataGridView1.GetCellCount(DataGridViewElementStates.Selected);

if (selectedCells > 0)
{
    StringBuilder cellStrBuilder = new StringBuilder();
    //loop through the selected cells, get their values and append to the string builder variable
    for(int i = 0; i < selectedCells; i++)
    {
        cellStrBuilder.Append(bunifuDataGridView1.SelectedCells[i].Value + "\t");
    }
    //output the seleccted cell values
    Console.WriteLine(cellStrBuilder);
}
```

{% endtab %}
{% endtabs %}

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-Mecz2wem-6WUqo-ghjE%2F-MegrpsEEzgaxSB4U1il%2Fimage.png?alt=media\&token=0c5a3335-cde9-4c63-ab9e-302b1072e8ab)

The selected values are printed in the output screen as follows:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-Mecz2wem-6WUqo-ghjE%2F-MegxIJDNIBRO_PbKOHM%2Fimage.png?alt=media\&token=ca4d97a9-9c83-4c52-98e8-e3a321c07468)

#### c) Header column selection

&#x20;`BunifuDataGridView` allows you to select or deselect rows within a specific column by interacting with the column's header cell. To set this type of selection set the `SelectionMode` prop to **`ColumnHeaderSelect.`**

{% hint style="info" %}
To make this type of selection work, ensure that the **`SortMode`** property for the textbox columns is set to programmatic. The sorting techniques will be discussed in greater detail later in this documentation.
{% endhint %}

To retrieve the selected values in a row, refer to the following code:

{% tabs %}
{% tab title="C#" %}

```csharp
private void Form3_Load(object sender, EventArgs e)
{
		 for (int i = 0; i < bunifuDataGridView1.Columns.Count; i++)
		 {
				//set the sort mode for all the textbox columns
				bunifuDataGridView1.Columns(i).SortMode = DataGridViewColumnSortMode.Programmatic;
		 }
		  bunifuDataGridView1.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
}
private void bunifuButton1_Click(object sender, EventArgs e)
{		// get the selected cells in the column
		  int selectedCells = bunifuDataGridView1.GetCellCount(DataGridViewElementStates.Selected);
		  StringBuilder strBuider = new StringBuilder();

		  for (int i = 0; i < selectedCells; i++)
		  {
				//get the selected cell values from the column
				strBuider.Append(bunifuDataGridView1.SelectedCells(i).Value + "\t");
		  }
				//output the selected values
			Console.WriteLine(strBuider);
}

```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Imports Microsoft.VisualBasic

Private Sub Form3_Load(ByVal sender As Object, ByVal e As EventArgs)
		 For i As Integer = 0 To bunifuDataGridView1.Columns.Count - 1
				bunifuDataGridView1.Columns(i).SortMode = DataGridViewColumnSortMode.Programmatic
		 Next i
		  bunifuDataGridView1.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect
End Sub
Private Sub bunifuButton1_Click(ByVal sender As Object, ByVal e As EventArgs)
		  Dim selectedCells As Integer = bunifuDataGridView1.GetCellCount(DataGridViewElementStates.Selected)
		  Dim strBuider As New StringBuilder()

		  For i As Integer = 0 To selectedCells - 1
				strBuider.Append(bunifuDataGridView1.SelectedCells(i).Value & vbTab)
		  Next i
			Console.WriteLine(strBuider)
End Sub

```

{% endtab %}
{% endtabs %}

#### d) Disable selection

&#x20;The selection can be disabled by setting the `Enabled` property to **`False`**.

{% hint style="danger" %}
When the Datagrid control is disabled, it becomes a read-only control.
{% endhint %}

### 5. Custom Tooltips&#x20;

There are instances where Datagrid cells contain extensive text content, and this information is hidden due to the cell's size. As a result, ToolTips are added to provide support for displaying the entire text content in a pop-up window that appears when the mouse hovers over the cells of a `BunifuDataGrid`.

The steps below demonstrate how we will override the standard DataGrid tooltip and replace it with a more customizable [Bunifu tooltip](https://docs2.bunifuframework.com/docs/ui/controls/bunifu-tooltip) control. It is assumed that you already have a Datagrid with data in its cells.

**Step one:** Drag and drop a [Bunifu Tooltip](https://docs2.bunifuframework.com/docs/ui/controls/bunifu-tooltip) control in the form.

**Step two:** Access the properties of `BunifuDataGrid` and look out for the **`ShowCellTooltips`**&#x70;roperty. Set it to **false**. This will enable us to add our own custom tooltip.

**Step three:** Go to the **event** properties of **`BunifuDataGrid`** and look out for the **`CellMouseEnter`** event. Double-click on its text area to navigate to the code view.

**Step four:** Write the following code:

{% tabs %}
{% tab title="C#" %}

```csharp
//the event gets fired when the mouse is over the cell
private void bunifuDataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
    /*
        * check whether the mouse is over the row cells of the datagrid.
        * this avoids the code below from executing when the mouse hovers on the column header cells and row header cells
    */
    if(e.ColumnIndex >= 0 & e.RowIndex >= 0)
    {
        //get the row datagrid cell currently hovered
        DataGridViewCell dataGridcell = bunifuDataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
        //get the display area or the location of the cell that is currently hovered
        var cellreactangle = bunifuDataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
        //check whether the cell has text content in it
        if (dataGridcell.Value != null)
        {
            //use bunifu tooltip to display the text content of the cell
             bunifuToolTip1.Show(bunifuDataGridView1, dataGridcell.Value.ToString(), bunifuDataGridView1.Columns[dataGridcell.ColumnIndex].HeaderText, null, bunifuDataGridView1.PointToScreen(new Point(cellreactangle.X + 80, cellreactangle.Y)));
        }
    }   
}
private void bunifuDataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
    bunifuToolTip1.Hide();
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Option Infer On

'the event gets fired when the mouse is over the cell
Private Sub bunifuDataGridView1_CellMouseEnter(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
'    
'        * check whether the mouse is over the row cells of the datagrid.
'        * this avoids the code below from executing when the mouse hovers on the column header cells and row header cells
'    
	If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
		'get the row datagrid cell currently hovered
		Dim dataGridcell As DataGridViewCell = bunifuDataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)
		'get the display area or the location of the cell that is currently hovered
		Dim cellreactangle = bunifuDataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True)
		'check whether the cell has text content in it
		If dataGridcell.Value IsNot Nothing Then
			'use bunifu tooltip to display the text content of the cell
			bunifuToolTip1.Show(bunifuDataGridView1, dataGridcell.Value.ToString(), "08/07/2021", Nothing, bunifuDataGridView1.PointToScreen(New Point(cellreactangle.X + 80, cellreactangle.Y)))
		End If
	End If
End Sub
Private Sub bunifuDataGridView1_CellMouseLeave(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
	bunifuToolTip1.Hide()
End Sub


```

{% endtab %}
{% endtabs %}

Step 5: Run your application. Here's is an example of our application running the codes above, the following output will occur:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-Mepu-iJdrDBZ_DE9LZS%2F-Mes2ExJoSsGwU_LaO_M%2Fdt12.gif?alt=media\&token=1993d980-74d1-46ef-a0ad-3182945a319f)

## Data Binding

`BunifuDataGrid` has been designed to support the use of bounded data.&#x20;

{% hint style="success" %}
Let us examine each feature in detail to ensure that we are maximizing the use of bounded data properties, methods, and events to the fullest extent possible.
{% endhint %}

Bunifu DataGrid View has data-binding support to work out-of-the-box with all popular data sources like SQL Server, Oracle, DataTable, and IEnumerable, and data providers like LINQ to SQL, ADO.NET, Entity Framework, and WCF Data Service.

&#x20;If the data source implements the [INotifyCollectionChanged](https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.inotifycollectionchanged?view=net-5.0) interface, then `BunifuDataGridView` will automatically refresh the UI when an item is added, removed, or while the list cleared.

### 1. Binding to a Generic Collection List

It's simple and clear to create a generic collection with binding properties, which results in bounded data. The following code illustrates how we can bind a collection of list objects with the BindingList Class to create tabular data for `BunifuDataGridView`

{% hint style="info" %}
Note that the column header names will be created automatically based on the property names given to the class objects.
{% endhint %}

Step 1: Create the following `OrderDemo` class  with its get and set properties:

{% tabs %}
{% tab title="C#" %}

```csharp
class OrderDemo
{
    private Guid order_Id=Guid.NewGuid();

    public Guid OrderID
      {
        get { return order_Id; }
        set { order_Id = value; }
      }
    public string ProductName { get; set; }
    public string CustomerName { get; set; }
    public string PhoneNumber { get; set; }
    public string ShippingCity { get; set; } 
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Public Class DemoOrder
	Private order_Id As Guid=Guid.NewGuid()
	
	Public Property OrderID() As Guid
		Get
			Return order_Id
		End Get
		Set(ByVal value As Guid)
			order_Id = value
		End Set
	End Property

	Public Property ProductName() As String
	Public Property CustomerName() As String
	Public Property PhoneNumber() As String
	Public Property ShippingCity() As String
End Class

```

{% endtab %}
{% endtabs %}

Step 2: In the form load event of your form write the following code:

{% tabs %}
{% tab title="C#" %}

```csharp
//the global variable provides the source of data for the Datagrid and where the generic list will be bound
BindingSource bindingSource = new BindingSource();
//the form load event containing out BunifuDataGridView
private void Form1_Load(object sender, EventArgs e)
{
    /*
      *the BindingList class is of type OrderDemo
      *has support to provide binding capabilities for a generic list
    */
    BindingList<OrderDemo> orderDemoList = new BindingList<OrderDemo>()
    {
        //add the class objects to the list, setting their properties
        new OrderDemo()
        {
            CustomerName="Tracy Ravis",
            PhoneNumber="(188)1863076",
            ShippingCity="Salt Lake City",
            ProductName="HP Envy x360 13 (2020)"
        },
        new OrderDemo()
        {
            CustomerName="Elsie Harris",
            PhoneNumber="(046)1938785",
            ShippingCity="Perth",
            ProductName="HP Envy 13 (2021)"
        },
        new OrderDemo()
        {
            CustomerName="Roger Craig",
            PhoneNumber="(042)9830172",
            ShippingCity="Australian Capital Territory",
            ProductName="HP Spectre x360 14"
        },
        new OrderDemo()
        {
            CustomerName="Danny Mckinney",
            PhoneNumber="(651)0438562",
            ShippingCity="Glendale",
            ProductName="HP EliteBook x360 1040 G7"
        },
        new OrderDemo()
        {
            CustomerName="Derrick Wade",
            PhoneNumber="(636)4728149",
            ShippingCity="San Bernardino",
            ProductName="HP Chromebook x2"
        }
    };
    //bind the list to the binding source
    bindingSource.DataSource = orderDemoList;
    //set the binding source as the data source for Bunifu DataGrid View
    bunifuDataGridView1.DataSource = bindingSource;
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
'the global variable provides the source of data for the Datagrid and where the generic list will be bound
Private bindingSource As New BindingSource()
'the form load event containing out BunifuDataGridView
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
'    
'      *the BindingList class is of type OrderDemo
'      *has support to provide binding capabilities for a generic list
'    
	Dim orderDemoList As New BindingList(Of OrderDemo)() From {
		New OrderDemo() With {
			.CustomerName="Tracy Ravis",
			.PhoneNumber="(188)1863076",
			.ShippingCity="Salt Lake City",
			.ProductName="HP Envy x360 13 (2020)"
		},
		New OrderDemo() With {
			.CustomerName="Elsie Harris",
			.PhoneNumber="(046)1938785",
			.ShippingCity="Perth",
			.ProductName="HP Envy 13 (2021)"
		},
		New OrderDemo() With {
			.CustomerName="Roger Craig",
			.PhoneNumber="(042)9830172",
			.ShippingCity="Australian Capital Territory",
			.ProductName="HP Spectre x360 14"
		},
		New OrderDemo() With {
			.CustomerName="Danny Mckinney",
			.PhoneNumber="(651)0438562",
			.ShippingCity="Glendale",
			.ProductName="HP EliteBook x360 1040 G7"
		},
		New OrderDemo() With {
			.CustomerName="Derrick Wade",
			.PhoneNumber="(636)4728149",
			.ShippingCity="San Bernardino",
			.ProductName="HP Chromebook x2"
		}
	}
	'bind the list to the binding source
	bindingSource.DataSource = orderDemoList
	'set the binding source as the data source for Bunifu DataGrid View
	bunifuDataGridView1.DataSource = bindingSource
End Sub

```

{% endtab %}
{% endtabs %}

Step 3: Run your application. Here's the output of the DataGrid running the codes above code:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-Mf-KokfiXLg6hyEOV3L%2F-Mf17RRTYxTtzos8j-zX%2Fimage.png?alt=media\&token=3d7fd77d-3c0a-42b6-a0b0-ab869d39cbe5)

### 2. Binding with a `DataTable`

&#x20;Binding with a `DataTable` is quite easy with`BunifuDataGridView.` Once your `DataTable` is set with the rows and columns, you just need to assign it to the `DataSource` property of `BunifuDataGridView`. The DataGrid control automatically refreshes the UI  when rows are added, removed, or cleared in the `DataTable`. Here's a code to bind the `DataTable` to `BunifuDataGridView.`

Step 1: Create the class with the get and set properties. We will use it and create a list of this class type to hold our table values.

{% tabs %}
{% tab title="C#" %}

```csharp
class OrderDemo
{
    private Guid order_Id=Guid.NewGuid();

    public Guid OrderID
      {
        get { return order_Id; }
        set { order_Id = value; }
      }
    public string ProductName { get; set; }
    public string CustomerName { get; set; }
    public string PhoneNumber { get; set; }
    public string ShippingCity { get; set; } 
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Public Class DemoOrder
	Private order_Id As Guid=Guid.NewGuid()
	
	Public Property OrderID() As Guid
		Get
			Return order_Id
		End Get
		Set(ByVal value As Guid)
			order_Id = value
		End Set
	End Property

	Public Property ProductName() As String
	Public Property CustomerName() As String
	Public Property PhoneNumber() As String
	Public Property ShippingCity() As String
End Class
```

{% endtab %}
{% endtabs %}

Step 2: In the Form load event, we will create the `DataTable` and assign it as a data source for `BunifuDataGridView`. Firstly write the following code to add the Order objects in a list:

{% tabs %}
{% tab title="C#" %}

```csharp
private void Form5_Load(object sender, EventArgs e)
{

    BindingList<OrderDemo> orderDemoList = new BindingList<OrderDemo>()
    {

        new OrderDemo()
        {
            CustomerName="Tracy Ravis",
            PhoneNumber="(188)1863076",
            ShippingCity="Salt Lake City",
            ProductName="HP Envy x360 13 (2020)"
        },
        new OrderDemo()
        {
            CustomerName="Elsie Harris",
            PhoneNumber="(046)1938785",
            ShippingCity="Perth",
            ProductName="HP Envy 13 (2021)"
        },
        new OrderDemo()
        {
            CustomerName="Roger Craig",
            PhoneNumber="(042)9830172",
            ShippingCity="Australian Capital Territory",
            ProductName="HP Spectre x360 14"
        },
        new OrderDemo()
        {
            CustomerName="Danny Mckinney",
            PhoneNumber="(651)0438562",
            ShippingCity="Glendale",
            ProductName="HP EliteBook x360 1040 G7"
        },
        new OrderDemo()
        {
            CustomerName="Derrick Wade",
            PhoneNumber="(636)4728149",
            ShippingCity="San Bernardino",
            ProductName="HP Chromebook x2"
        }
    };
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Private Sub Form5_Load(ByVal sender As Object, ByVal e As EventArgs)

	Dim orderDemoList As New BindingList(Of OrderDemo)() From {
		New OrderDemo() With {
			.CustomerName="Tracy Ravis",
			.PhoneNumber="(188)1863076",
			.ShippingCity="Salt Lake City",
			.ProductName="HP Envy x360 13 (2020)"
		},
		New OrderDemo() With {
			.CustomerName="Elsie Harris",
			.PhoneNumber="(046)1938785",
			.ShippingCity="Perth",
			.ProductName="HP Envy 13 (2021)"
		},
		New OrderDemo() With {
			.CustomerName="Roger Craig",
			.PhoneNumber="(042)9830172",
			.ShippingCity="Australian Capital Territory",
			.ProductName="HP Spectre x360 14"
		},
		New OrderDemo() With {
			.CustomerName="Danny Mckinney",
			.PhoneNumber="(651)0438562",
			.ShippingCity="Glendale",
			.ProductName="HP EliteBook x360 1040 G7"
		},
		New OrderDemo() With {
			.CustomerName="Derrick Wade",
			.PhoneNumber="(636)4728149",
			.ShippingCity="San Bernardino",
			.ProductName="HP Chromebook x2"
		}
	}
End Sub

```

{% endtab %}
{% endtabs %}

Secondly, write the following code snippet to create a DataTable and assign columns and rows to it:

{% tabs %}
{% tab title="C#" %}

```csharp
DataTable dataTable = new DataTable();
//create an array of table columns
DataColumn[] tableColumns = new DataColumn[]
{
    new DataColumn()
    {
        ColumnName="Order_ID",
        DataType=typeof(string),
    },
    new DataColumn()
    {
        ColumnName="Product Name",
        DataType=typeof(string),
    },
    new DataColumn()
    {
        ColumnName="Customer Name",
        DataType=typeof(string),
    },
    new DataColumn()
    {
        ColumnName="Phone Number",
        DataType=typeof(string),
    },
    new DataColumn()
    {
        ColumnName="Shipping City",
        DataType=typeof(string),
    }

};    
dataTable.Columns.AddRange(tableColumns);
//loop through the  each of the order objects in the list and get their prop values
foreach(var data in orderDemoList)
{
    dataTable.Rows.Add(data.OrderID, data.ProductName, data.CustomerName, data.PhoneNumber, data.ShippingCity);
}
//bind the data table to Bunifu DataGridView
bunifuDataGridView1.DataSource = dataTable;
```

{% endtab %}

{% tab title="VB.NET" %}

```
Option Infer On

Dim dataTable As New DataTable()
'create an array of table columns
Dim tableColumns() As DataColumn = {
	New DataColumn() With {
		.ColumnName="Order_ID",
		.DataType=GetType(String)
	},
	New DataColumn() With {
		.ColumnName="Product Name",
		.DataType=GetType(String)
	},
	New DataColumn() With {
		.ColumnName="Customer Name",
		.DataType=GetType(String)
	},
	New DataColumn() With {
		.ColumnName="Phone Number",
		.DataType=GetType(String)
	},
	New DataColumn() With {
		.ColumnName="Shipping City",
		.DataType=GetType(String)
	}
}
dataTable.Columns.AddRange(tableColumns)
'loop through the  each of the order objects in the list and get their prop values
For Each data In orderDemoList
	dataTable.Rows.Add(data.OrderID, data.ProductName, data.CustomerName, data.PhoneNumber, data.ShippingCity)
Next data
bunifuDataGridView1.DataSource = dataTable

```

{% endtab %}
{% endtabs %}

Here's the output upon running the codes above:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfIPzTwYDgf1wFDvtjt%2F-MfIQmbqJURQ_xvaZJmG%2Fdt13.gif?alt=media\&token=22866ae9-30fc-4ced-bf75-4cc77a2579e3)

### 3. Binding to XML Data

&#x20;We can load data easily from an XML file to`BunifuDataGridView.` This can be achieved by using the [DataSet](https://docs.microsoft.com/en-us/dotnet/api/system.data.dataset?view=net-5.0) object which provides the necessary methods that are used to read XML data into the dataset.&#x20;

&#x20;To generate an XML file, right-click the project's name in the solution explorer tab and select the add option. In the pop-up window displayed navigate to the Data tab and select the XML File item.&#x20;

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfJqLfLKK7R2Gx7UoGL%2F-MfJwzJB8SaZNRTumD2d%2Fimage.png?alt=media\&token=039fd596-ec05-480a-a1f3-6d506ad0e827)

&#x20;The following is an example of XML Data that we will bind to `BunifuDataGridView`.

{% tabs %}
{% tab title="XML" %}

```markup
<?xml version="1.0" encoding="utf-8" ?>
<Invoice>
    <Item>
      <Item_Number>001</Item_Number>
      <Item_Name>MacBook Air</Item_Name>
      <Item_Price>$999</Item_Price>
    </Item>
    <Item>
      <Item_Number>002</Item_Number>
      <Item_Name>MacBook Pro 13</Item_Name>
      <Item_Price>$999</Item_Price>
    </Item>
    <Item>
      <Item_Number>003</Item_Number>
      <Item_Name>MacBook Pro 16”</Item_Name>
      <Item_Price>$999</Item_Price>
    </Item>
    <Item>
      <Item_Number>004</Item_Number>
      <Item_Name>Iphone 12 Pro</Item_Name>
      <Item_Price>$999</Item_Price>
    </Item>
    <Item>
      <Item_Number>005</Item_Number>
      <Item_Name>Iphone 12</Item_Name>
      <Item_Price>$699</Item_Price>
    </Item>
    <Item>
      <Item_Number>006</Item_Number>
      <Item_Name>Iphone 11</Item_Name>
      <Item_Price>$599</Item_Price>
    </Item>
</Invoice>
```

{% endtab %}
{% endtabs %}

Write the following code in the form load event to read the above XML file and display the data in `BunifuDataGridView`:

{% tabs %}
{% tab title="C#" %}

```csharp
private void Form6_Load(object sender, EventArgs e)
{
    DataSet dataSet = new DataSet();
    //get the current directory path
    string currentPath = Directory.GetCurrentDirectory();
    //get two folders up to the assembly folder
    string newPath = Path.GetFullPath(Path.Combine(currentPath, @"..\..\"));
    //get the xml file
    dataSet.ReadXml(newPath + @"/InvoiceXML.xml");
    //bind the xml to Bunifu DataGridView
    bunifuDataGridView1.DataSource = dataSet.Tables[0];
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Private Sub Form6_Load(ByVal sender As Object, ByVal e As EventArgs)
	Dim dataSet As New DataSet()
	'get the current directory path
	Dim currentPath As String = Directory.GetCurrentDirectory()
	'get two folders up to the assembly folder
	Dim newPath As String = Path.GetFullPath(Path.Combine(currentPath, "..\..\"))
	'get the xml file
	dataSet.ReadXml(newPath & "/InvoiceXML.xml")
	bunifuDataGridView1.DataSource = dataSet.Tables(0)
End Sub

```

{% endtab %}
{% endtabs %}

Here's the output of the above code:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfK9sJH7g17sNbYVs_u%2F-MfKYdoqKp2NGU-B8Q-K%2Fimage.png?alt=media\&token=0c432947-092a-4606-9e32-4fd4c8e44e04)

{% hint style="info" %}
It is also possible to save the changes back to the XML file.
{% endhint %}

### 4. Binding Data from ADO.NET Framework Entity

&#x20;**`BunifuDataGridView`** provides the support to bind data from an **ADO.NET Entity Framework**. The ADO.NET entity framework is a database access technology that contains object-oriented classes to create high performance when accessing any kind of data source.&#x20;

ADO .NET uses SQL queries and stored procedures to read write update and delete data from a data source. This walk-through describes binding data from ADO.NET Entity Framework and saving back the changes to the database.

#### Step 1: Create a data model using the entity framework.&#x20;

To create the data model:

a) Right-click the project's name in the solution explorer, select the **Add** option, then click on **New Item.**

b) In the pop-up wizard displayed, select the **Data** node, then select the **`ADO.NET Entity Data Mode`** item and click the add button.

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfY9yLBuby0DhphQHOC%2F-MfYDpBeOQq70G8k29qn%2Fimage.png?alt=media\&token=e39ce1a9-65f1-4e8e-9876-26ab50471760)

c) Next, on the wizard displayed as shown below, select the   **EF Designer from database** option and then click **Next**.

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfY9yLBuby0DhphQHOC%2F-MfYF0lRT2U6O5Y4UvkH%2Fimage.png?alt=media\&token=e7bfd637-728e-4424-848c-0d3790d695f4)

d) In the Choose Your Data Connection wizard, click the new connection button, select Microsoft SQL SERVER as the data source and click the continue button. To configure/modify connection, refer: [How to: Create Connections to SQL Server Databases.](https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2008/s4yys16a\(v=vs.90\))

{% hint style="info" %}
This section assumes that you already have a database in your SQL Server. It is important to ensure that you have installed the [Microsoft SQL Express Server](https://go.microsoft.com/fwlink/?linkid=866658) and its management studio.
{% endhint %}

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfY9yLBuby0DhphQHOC%2F-MfZBOVI8mxLQv9xDqZT%2FDTI001.png?alt=media\&token=be9d6cbb-567d-41d4-84df-0fad3de46089)

Click the OK button after successfully testing the connection.

e) In the choose your data connection Click the Next button . Ensure that you have a connection string displayed on the window and you have enabled/checked the save connection setting option.

f) In the next window select Entity version **6.x** as the version entity framework to use, then click the next button.

g) Select the tables that you want to include in your entity model and click the on the finish button.

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfY9yLBuby0DhphQHOC%2F-MfZFaX02APp7sPhwW55%2Fimage.png?alt=media\&token=b8576468-a24a-4c54-8281-bd4e470ad3b4)

Once it has finished creating the model, the following diagram will appear as follows in your visual studio:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfY9yLBuby0DhphQHOC%2F-MfZJXHIBBXHySGNkxgR%2Fimage.png?alt=media\&token=8be37f28-67e0-4a6b-8dc6-d8d1de28647f)

#### Step 2: Loading data from the model to BunifuDataGridView:

To bind the data from the entity model, write the following code in the form load event:

{% tabs %}
{% tab title="C#" %}

```csharp
private void Form1_Load(object sender, EventArgs e)
{
  //instantiate the entity created from the wizard
  BuniEntities buniEntities = new BuniEntities();
  //load the table data from the database
  buniEntities.Orders.Load();//use System.Data.Entity for the load method
 
   //bind the data to Bunifu DataGridView
  /*the local property provides access to the data 
   * without a query being sent to the database
  */
  bunifuDataGridView1.DataSource = buniEntities.Orders.Local.ToBindingList();
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
  'instantiate the entity created from the wizard
  Dim buniEntities As New BuniEntities()
  'load the table data from the database
  buniEntities.Orders.Load() 'use System.Data.Entity for the load method

   'bind the data to Bunifu DataGridView
'  the local property provides access to the data 
'   * without a query being sent to the database
'  
  bunifuDataGridView1.DataSource = buniEntities.Orders.Local.ToBindingList()
End Sub

```

{% endtab %}
{% endtabs %}

The following is the output of the above code where the data has been loaded from the database:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfZWREdIg6Hbty9uW91%2F-MfZWzZElflRU7qge1Wn%2Fimage.png?alt=media\&token=c191ce7c-7b13-462f-9fb8-7db8bed0368f)

To update a cell value and reflect the changes in the database, write the following code in the `cellEndEdit` event of `BunifuDataGridView`

{% tabs %}
{% tab title="C#" %}

```csharp
private void bunifuDataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    //get the cell that has the primary key
    int primaryKey= Convert.ToInt32(bunifuDataGridView1.Rows[e.RowIndex].Cells[0].Value);

    //get the column name where the cell is currently modified
    string columnName = bunifuDataGridView1.Columns[e.ColumnIndex].HeaderText;

    //get the cell value modified
    string editedValue = bunifuDataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
   
    switch (columnName)
    {

        case "ProductName":
            //update the entity model object with a new value
            buniEntities.Orders.Find(primaryKey).ProductName = editedValue;
            //save the changes in the database
            buniEntities.SaveChanges();
            bunifuSnackbar1.Show(this, "Changes effected on one row", BunifuSnackbar.MessageTypes.Information, 1200, null, BunifuSnackbar.Positions.MiddleCenter);
            break;
        case "CustomerName":
            buniEntities.Orders.Find(primaryKey).CustomerName = editedValue;
            buniEntities.SaveChanges();
            bunifuSnackbar1.Show(this, "Changes effected on one row", BunifuSnackbar.MessageTypes.Information, 1200, null, BunifuSnackbar.Positions.MiddleCenter);
            break;
        case "ShippingCity":
            buniEntities.Orders.Find(primaryKey).ShippingCity = editedValue;
            bunifuSnackbar1.Show(this, "Changes effected on one row", BunifuSnackbar.MessageTypes.Information, 1200, null, BunifuSnackbar.Positions.MiddleCenter);
            buniEntities.SaveChanges();
            break;
        case "State":
            buniEntities.Orders.Find(primaryKey).State = editedValue;
            buniEntities.SaveChanges();
            break;
        case "Quantity":
            buniEntities.Orders.Find(primaryKey).Quantity = Convert.ToInt32(editedValue);
            bunifuSnackbar1.Show(this, "Changes effected on one row", BunifuSnackbar.MessageTypes.Information, 1200, null, BunifuSnackbar.Positions.MiddleCenter);
            buniEntities.SaveChanges();
            break;
        case "UnitPrice":
            buniEntities.Orders.Find(primaryKey).UnitPrice = Convert.ToInt32(editedValue);
            buniEntities.SaveChanges();
            bunifuSnackbar1.Show(this, "Changes effected on one row", BunifuSnackbar.MessageTypes.Information, 1200, null, BunifuSnackbar.Positions.MiddleCenter);
            break;
        default:
            break;
    }
  
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Private Sub bunifuDataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
	'get the cell that has the primary key
	Dim primaryKey As Integer= Convert.ToInt32(bunifuDataGridView1.Rows(e.RowIndex).Cells(0).Value)

	'get the column name where the cell is currently modified
	Dim columnName As String = bunifuDataGridView1.Columns(e.ColumnIndex).HeaderText

	'get the cell value modified
	Dim editedValue As String = bunifuDataGridView1(e.ColumnIndex, e.RowIndex).Value.ToString()

	Select Case columnName

		Case "ProductName"
			'update the entity model object with a new value
			buniEntities.Orders.Find(primaryKey).ProductName = editedValue
			'save the changes in the database
			buniEntities.SaveChanges()
			bunifuSnackbar1.Show(Me, "Changes effected on one row", BunifuSnackbar.MessageTypes.Information, 1200, Nothing, BunifuSnackbar.Positions.MiddleCenter)
		Case "CustomerName"
			buniEntities.Orders.Find(primaryKey).CustomerName = editedValue
			buniEntities.SaveChanges()
			bunifuSnackbar1.Show(Me, "Changes effected on one row", BunifuSnackbar.MessageTypes.Information, 1200, Nothing, BunifuSnackbar.Positions.MiddleCenter)
		Case "ShippingCity"
			buniEntities.Orders.Find(primaryKey).ShippingCity = editedValue
			bunifuSnackbar1.Show(Me, "Changes effected on one row", BunifuSnackbar.MessageTypes.Information, 1200, Nothing, BunifuSnackbar.Positions.MiddleCenter)
			buniEntities.SaveChanges()
		Case "State"
			buniEntities.Orders.Find(primaryKey).State = editedValue
			buniEntities.SaveChanges()
		Case "Quantity"
			buniEntities.Orders.Find(primaryKey).Quantity = Convert.ToInt32(editedValue)
			bunifuSnackbar1.Show(Me, "Changes effected on one row", BunifuSnackbar.MessageTypes.Information, 1200, Nothing, BunifuSnackbar.Positions.MiddleCenter)
			buniEntities.SaveChanges()
		Case "UnitPrice"
			buniEntities.Orders.Find(primaryKey).UnitPrice = Convert.ToInt32(editedValue)
			buniEntities.SaveChanges()
			bunifuSnackbar1.Show(Me, "Changes effected on one row", BunifuSnackbar.MessageTypes.Information, 1200, Nothing, BunifuSnackbar.Positions.MiddleCenter)
		Case Else
	End Select

End Sub

```

{% endtab %}
{% endtabs %}

The output of the above code will be as follows:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfZXGXhvUIq-MY9s34G%2F-Mfby8tRsEOgo33GEV3L%2Fdt15.gif?alt=media\&token=4c9cbe73-be39-46ea-8965-ef9d8bc0b30d)

{% hint style="info" %}
You can use SQL Queries and Linq to update, create, read and update data in the ADO.NET Entity Framework
{% endhint %}

The following example shows how to retrieve the orders data using an SQL Query and bind the data in`BunifuDataGridView` using the form load event`:`

{% tabs %}
{% tab title="C#" %}

```csharp
private void Form6_Load(object sender, EventArgs e)
    {
        //instantiate the entity created from the wizard
        BuniEntities buniEntities = new BuniEntities();
        //execute the sql query to retrieve the data
        var ordersData= buniEntities.Database.SqlQuery<BunifuData.Order>("Select * From Orders").ToList();
        //bind the retrieved data to the datagrid view
        bunifuDataGridView1.DataSource = ordersData;
    }

```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Option Infer On

Private Sub Form6_Load(ByVal sender As Object, ByVal e As EventArgs)
		'instantiate the entity created from the wizard
		Dim buniEntities As New BuniEntities()
		'execute the sql query to retrieve the data
		Dim ordersData= buniEntities.Database.SqlQuery(Of BunifuData.Order)("Select * From Orders").ToList()
		'bind the retrieved data to the datagrid view
		bunifuDataGridView1.DataSource = ordersData
End Sub

```

{% endtab %}
{% endtabs %}

**References:**\
<https://docs.microsoft.com/en-us/ef/ef6/fundamentals/databinding/winforms>

### 5. Binding Data from MySQL Database (Using [Micron](https://kimtooflex.gitbook.io/workspace/))

The Micron library allows us to easily query data from both MySQL and MariaDB database engines. It automatically creates models that match your database schema. To install and configure the Micron library, refer: [How to install the Micron ORM library](https://kimtooflex.gitbook.io/workspace/installation).

Below is the walk-through that describes binding data from the MySQL database using the Micron ORM Framework and saving back the changes to the database.

#### Step 1: Connecting to MySQL Database:

To connect to a MySQL database :

{% hint style="info" %}
First, download the demo database file below and import it in your MySQL database.
{% endhint %}

{% file src="<https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfcFp56VbgUbrNyrcaI%2F-Mfdm8RG1L2SDmZOVy8k%2Finventory.sql?alt=media&token=609d150f-1320-478a-a1cb-a8cd9c68e4d2>" %}
Demo Inventory Database
{% endfile %}

b) Write the following code in the main entry point of your application:

{% tabs %}
{% tab title="C#" %}

```csharp
using Micron;
static void Main()
{    //the connection configuration file
    MicronConfig connectionConfig = new MicronConfig()
    {
        Host="localhost",
        User="root",
        Password="",
        Port="8080",
        DatabaseName="inventory"
    };
    MicronDbContext.AddConnectionSetup(connectionConfig);
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Imports Micron
Shared Sub Main() 'the connection configuration file
	Dim connectionConfig As New MicronConfig() With {
		.Host="localhost",
		.User="root",
		.Password="",
		.Port="8080",
		.DatabaseName="inventory"
	}
	MicronDbContext.AddConnectionSetup(connectionConfig)
End Sub

```

{% endtab %}
{% endtabs %}

c)  Open Nuget **Package Manager Console** and execute command below:      &#x20;

&#x20;      `update-micron database-first`

This tests the connection set above and on a successful connection it creates the models matching the database schema

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfcFp56VbgUbrNyrcaI%2F-Mfe-JrZmtbnF78xomab%2Fimage.png?alt=media\&token=94cb81db-88f7-4567-9d44-0abeeb653b9d)

The following folder will be created with the models from the database tables:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfcFp56VbgUbrNyrcaI%2F-Mfe61SUR71MrLoYSQYV%2Fimage.png?alt=media\&token=5485d96c-4aa9-4e6b-9ecf-f272bbb22b9e)

#### Step 2: Loading data from the customers model to `BunifuDataGridView`

Micron returns **IEnumerable\<T>** interface when retrieving data from a model. Write the following code to select data from the customers table:

{% tabs %}
{% tab title="C#" %}

```csharp
private void Form1_Load(object sender, EventArgs e)
{   //create the db context to access data from the database     
    MicronDbContext dbContext = new MicronDbContext();
    //retrieve data from the customer table
    var customers = dbContext.GetRecords<Data.Models.Customer>();
    //bind the data to Bunifu DataGridView
    bunifuDataGridView1.DataSource = customers.Select(x => new {
        x.CustomerID,
        x.CustomerName,
        x.ContactName,
        x.City,
        x.Country
    }).ToList();
}
}
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
Option Infer On

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) 'create the db context to access data from the database
	Dim dbContext As New MicronDbContext()
	'retrieve data from the customer table
	Dim customers = dbContext.GetRecords(Of Data.Models.Customer)()
	'bind the data to Bunifu DataGridView
	bunifuDataGridView1.DataSource = customers.Select(Function(x) New With {
		Key x.CustomerID,
		Key x.CustomerName,
		Key x.ContactName,
		Key x.City,
		Key x.Country
	}).ToList()
End Sub
}

```

{% endtab %}
{% endtabs %}

The above code outputs the following MySQL data in the Datagrid:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfcFp56VbgUbrNyrcaI%2F-MfeNHtY2ulgwpnihoPI%2Fimage.png?alt=media\&token=74b237fa-f609-4a40-a756-c3b33d0f19a0)

## Data virtualization

&#x20;**`BunifuDataGridView`** provides support to handle a large amount of data through built-in virtualization features.&#x20;

With Data virtualization, there is the processing of the data in on-demand for better performance while loading a large amount of data. A large amount of data can be loaded in less time by setting **`VirtualMode`** property to **`true`**.

## Exporting Data to PDF(using Bunifu Reports)

Bunifu reports is a special kind of reporting tool that can be integrated seamlessly into your visual studio project. It allows you as a developer to add the reporting module that can generate pdf content from any .NET control that conveys data to the user.

To install and configure Bunifu reports, refer to [NuGet Gallery | Bunifu.Reports 1.0.5](https://www.nuget.org/packages/Bunifu.Reports/)

Below is the walk-through that describes how to export BunifuDatagridView content to a PDF file using Bunifu reports:

**Step one:** In the design view, drag and drop a Bunifu report component from the toolbox to your form.

**Step two:** Have your `BunifuDatagridView` populated with ready data from any data source.

**Step three:** Create a save button in your form and double click it to navigate to the code view.

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfjZC8DGwYdakAqq9C4%2F-MfjbqKntw0CWwOSAFBP%2Fimage.png?alt=media\&token=4f2af577-9fa8-452f-8208-d79499ddfe21)

**Step four**: Write the following code in the **click** event of the button:

{% tabs %}
{% tab title="C#" %}

```csharp
 private void bunifuButton1_Click(object sender, EventArgs e)
 {
     /*add a label control from the form
      * this will take all the property styles used in the label
      * and apply them in the report
     */
     bunifuReports1.AddControl(titleBunifuLabel);
     //add some line breaks to create a space before rendering the next control
     bunifuReports1.AddLineBreak();
     bunifuReports1.AddLineBreak();
     /*
      * add Bunifu DataGridView control to the form
      * with the use of the AddDataGridView method
      * the first parameter is the Datagrid control
      * while the second parameter is the customization of the control rendered 
      * in the report
     */
     bunifuReports1.AddDatagridView(bunifuDataGridView1, "border=0;");
     //instantiate the save file dialog class to save the report as a pdf
     SaveFileDialog saveFile = new SaveFileDialog();
     //add the save file dialog component to the form
     this.components.Add(saveFile);
     //add a save as file type filter
     saveFile.Filter = "PDF(*.pdf)|*.pdf";
     //display the dialog and execute the code below when the ok button is pressed
    if(saveFile.ShowDialog() == DialogResult.OK)
     {
         //get the path where the pdf file will be saved
         string path = Path.GetFullPath(saveFile.FileName);
         //use the SavePDF method of Bunifu reports component to save the file
         //inside the method we shall pass the path  where the pdf will be saved
         bunifuReports1.SavePDF(path);
     }
}
          
```

{% endtab %}

{% tab title="VB.NET" %}

```erlang
 Private Sub bunifuButton1_Click(ByVal sender As Object, ByVal e As EventArgs)
'     add a label control from the form
'      * this will take all the property styles used in the label
'      * and apply them in the report
'     
	 bunifuReports1.AddControl(titleBunifuLabel)
	 'add some line breaks to create a space before rendering the next control
	 bunifuReports1.AddLineBreak()
	 bunifuReports1.AddLineBreak()
'     
'      * add Bunifu DataGridView control to the form
'      * with the use of the AddDataGridView method
'      * the first parameter is the Datagrid control
'      * while the second parameter is the customization of the control rendered 
'      * in the report
'     
	 bunifuReports1.AddDatagridView(bunifuDataGridView1, "border=0;")
	 'instantiate the save file dialog class to save the report as a pdf
	 Dim saveFile As New SaveFileDialog()
	 'add the save file dialog component to the form
	 Me.components.Add(saveFile)
	 'add a save as file type filter
	 saveFile.Filter = "PDF(*.pdf)|*.pdf"
	 'display the dialog and execute the code below when the ok button is pressed
	If saveFile.ShowDialog() = DialogResult.OK Then
		 'get the path where the pdf file will be saved
		 Dim path As String = System.IO.Path.GetFullPath(saveFile.FileName)
		 'use the SavePDF method of Bunifu reports component to save the file
		 'inside the method we shall pass the path  where the pdf will be saved
		 bunifuReports1.SavePDF(path)
	End If
 End Sub

```

{% endtab %}
{% endtabs %}

Here's an output of a pdf generated DatagridView report:

![](https://1116551356-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M7fmEPVv4n0I819sdaz%2F-MfjSe6XepJMzxFZRJ5h%2F-MfjWjPhldvriHBTfYex%2Fimage.png?alt=media\&token=8f4f1c1a-43df-46ff-bd34-860359499cc9)

## Take Away

We hope you have gained insights into using `BunifuDataGridView` and that the knowledge will help you create a better tabular data application interface for your users. Should you have feedback or suggestions, please send us via chat on the bottom right corner of the screen.
