A DataSet is one of the main components of ADO.Net infrastructure that can be used to store in memory data obtained from various sources. In a DataSet data is stored in a DataTable that can be linked with DataRelation.
The grid can connect to a DataTable directly or via a new .Net 2.0 class - BindingSource. This class has BindingSource.Current property and event that notifies the grid of changes in this property. When current is changed in master BindingSource and if DataRelation, child is present BindingSource notifies the grid via IBindingList.ListChanged. Please see below an example that demonstrates operation of grids linked with BindingSource.
C# | Copy |
---|---|
public static DataSet CreateDataSet() { // create a DataSet with one table, two columns DataSet dataSet = new DataSet(); // create Customer table DataTable table = new DataTable("Customers"); dataSet.Tables.Add(table); table.Columns.Add("customerId", typeof (int)).AutoIncrement = true; table.Columns.Add("name", typeof (string)); table.PrimaryKey = new DataColumn[] {table.Columns["customerId"]}; // create Orders table table = new DataTable("Orders"); dataSet.Tables.Add(table); table.Columns.Add("orderId", typeof (int)).AutoIncrement = true; table.Columns.Add("customerId", typeof (int)); table.Columns.Add("amount", typeof (double)); table.PrimaryKey = new DataColumn[] {table.Columns["orderId"]}; // create relation DataRelation relation = dataSet.Relations.Add("myrelation", dataSet.Tables["Customers"].Columns["customerId"], dataSet.Tables["Orders"].Columns["customerId"]); // populate the tables int orderId = 1; for (int customerId = 1; customerId <= 10; customerId++) { // add customer record dataSet.Tables["Customers"].Rows.Add(new object[] {customerId, string.Format("customer{0}", customerId)}); // add 5 order records for each customer for (int i = 1; i <= 5; i++) { dataSet.Tables["Orders"].Rows.Add(new object[] {orderId++, customerId, orderId*10}); } } return dataSet; } |
2. Initialize grids and setup relation
C# | Copy |
---|---|
public void InitializeGrids(Grid grid1, Grid grid2) { DataSet dataSet = CreateDataSet(); BindingSource source1 = new BindingSource(); BindingSource source2 = new BindingSource(); source1.DataSource = dataSet; source1.DataMember = "Customers"; source2.DataSource = source1; source2.DataMember = "myrelation"; //Master table grid1.Headers.AutoGenerate = true; grid1.DataSource = source1; //Orders table grid2.Headers.AutoGenerate = true; grid2.DataSource = source2; } |
Back to .Net Grid HowTo topics