[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Build a DataTable and bind it to a DataGridView

Build a DataTable and bind it to a DataGridView

This example shows how you can build a DataTable and bind it to a DataGridView control. A DataTable is an in-memory representation of a relational database table. It can define columns of particular data types and even enforce uniqueness and foreign key constraints. This example shows how to build a DataTable in code that uses specific data types for its columns and that has a two-column uniqueness constraint.

When the program starts, the following code creates and displays the DataTable.

private void Form1_Load(object sender, EventArgs e) { // Make the DataTable object. DataTable dt = new DataTable("People"); // Add columns to the DataTable. dt.Columns.Add("First Name", System.Type.GetType("System.String")); dt.Columns.Add("Last Name", System.Type.GetType("System.String")); dt.Columns.Add("Occupation", System.Type.GetType("System.String")); dt.Columns.Add("Salary", System.Type.GetType("System.Int32")); // Make all columns required. for (int i = 0; i < dt.Columns.Count; i++) { dt.Columns[i].AllowDBNull = false; } // Make First Name + Last Name require uniqueness. DataColumn[] unique_cols = { dt.Columns["First Name"], dt.Columns["Last Name"] }; dt.Constraints.Add(new UniqueConstraint(unique_cols)); // Add items to the table. dt.Rows.Add(new object[] {"Rod", "Stephens", "Nerd", 10000}); dt.Rows.Add(new object[] {"Sergio", "Aragones", "Cartoonist", 20000}); dt.Rows.Add(new object[] {"Eoin", "Colfer", "Author", 30000}); dt.Rows.Add(new object[] {"Terry", "Pratchett", "Author", 40000}); // Make the DataGridView use the DataTable as its data source. dgvPeople.DataSource = dt; }

This code makes a DataTable object and adds columns to it, specifying their data types. It then loops through all of the columns setting their AllowDBNull properties to false so each column is required.

Next the program makes an array containing the First Name and Last Name columns. It uses that array to make a UniqueConstraint object and adds it to the DataTable object's Constraints collection.

Finally the program uses the DataTable's Rows.Add method to add arrays of objects to the DataTable. It finishes by setting the DataGridView control's DataSource property to the DataTable. The DataGridView and DataTable display the data automatically.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.