Bind DataTable Columns to DataGridView: Step-by-Step Guide

├Źndice
  1. Introduction
  2. Step 1 - Create a DataTable
  3. Step 2 - Add Rows to DataTable
  4. Step 3 - Bind DataTable to DataGridView
  5. Conclusion

Introduction

In this step-by-step guide, we will explain how to bind DataTable columns to a DataGridView using C# programming language. DataTable is a powerful data structure in C# that can hold multiple rows and columns of data. DataGridView is a user interface control that displays data in a tabular format.

Step 1 - Create a DataTable

The first step is to create a DataTable and add columns to it. This can be done using the following code:


DataTable dataTable = new DataTable();
dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Age", typeof(int));

In this example, we have created a DataTable with three columns: ID, Name, and Age.

Step 2 - Add Rows to DataTable

The next step is to add rows to the DataTable. This can be done using the following code:


dataTable.Rows.Add(1, "John", 25);
dataTable.Rows.Add(2, "Jane", 30);
dataTable.Rows.Add(3, "Mark", 35);

In this example, we have added three rows to the DataTable.

Step 3 - Bind DataTable to DataGridView

The final step is to bind the DataTable to the DataGridView. This can be done using the following code:


dataGridView1.DataSource = dataTable;

In this example, we have set the DataSource property of the DataGridView to the DataTable created in Step 1.

Conclusion

In this step-by-step guide, we have explained how to bind DataTable columns to a DataGridView using C# programming language. By following these simple steps, you can display data in a tabular format in your application.

Click to rate this post!
[Total: 0 Average: 0]

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information