- This topic explains how to create DataTable at runtime and bind it to the DataGridView in C#.
- For this example in C#, we need only a DataGridView Control and also need to declare DataTable in C# form.
Working of DataTable – Create DataTable at runtime and bind to DataGridView in C#
- A DataSet is made up of a collection of Tables, relations and constraints.
- DataTable is used to represent Tables in DataSet.
- The DataTable class is a member of System.Data namespace.
- A DataTable represents one table of in-memory relation data.
- You can access the collections of tables in DataSet through the table property of the DataSet object.
- Datatable can be created and used independently.
- DataTable can be used by other .NET Framework objects.
Example to create a DataTable in C#
|
1 |
DataTable dt = new DataTable("Student"); |
Example to create DataTable by adding it to the Table collections of DataSet
|
1 2 |
DataSet customers = new DataSet(); DataTable customersTable = customers.Tables.Add("CustomersTable"); |
DataGridView in C# - Create DataTable at runtime and bind to DataGridView in C#
- The DataGridView in C# control provides a customizable table for displaying data.
- DataGridView in C# control is designed to be a complete solution for displaying tabular data with Windows Forms.
- DataGridView class in C# allows us to customization of cells, rows, columns, and borders through the use of its properties
- Each cell within the DataGridView control in C# can have its own style, such as text format, background color, foreground color, font etc.
- All cells derive from the DataGridViewCell base class.
Create DataTable at runtime and bind to DataGridView in C# – Working
- When a form loads, it creates a datatable dt and add columns using Add method(Columns.Add).
- Then add rows using Add method (Rows.Add).
- Finally assign the values of the datatable to the datagrid using DataSource property of dataGridView.
Create DataTable at runtime and bind to DataGridView in C# – Complete Code
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace textc { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { DataTable dt = new DataTable("Student"); dt.Columns.Add("Name"); dt.Columns.Add("Class"); dt.Columns.Add("Grade"); dt.Rows.Add("Stefen", "IV", "A+"); dt.Rows.Add("Ramesh", "VIII", "B+"); dt.Rows.Add("Rahul", "XI", "A"); dt.Rows.Add("Sam", "III", "C"); dataGridView1.DataSource = dt; } } } |
Create DataTable at runtime and bind to DataGridView in C#






