BLOG.CSHARPHELPER.COM: Make a DataTable in code and bind it to a DataGridView control in C#
Make a DataTable in code and bind it to a DataGridView control in C#
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.
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 the First Name/Last Name combination require uniqueness. DataColumn[] unique_cols = { dt.Columns["First Name"], dt.Columns["Last Name"] }; dt.Constraints.Add(new UniqueConstraint(unique_cols));
// Make the DataGridView use the DataTable as its data source. dgvPeople.DataSource = dt; }
When its form loads, the program 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's Constraints collection.
Finally the program uses the DataTable's Rows collection's Add method to add arrays of objects to the DataTable. It finishes by setting the DataGridView's DataSource property to the DataTable. The DataTable does the rest automatically.
Comments