Today I am going to show you how to bind
parent/child relation in windows form gridview. It’s very easy to show
parent/child relation in grid using third party controls but I want to show relation
without using additional controls. I found related help from internet but I like to show parent-child relation by adding DataSet relation on datacolums of DataTable.
C# Code:
private void BindGridView()
{
// Create
Tables
DataTable
tblCustomer = new DataTable("tblCustomer");
DataTable
tblOrder = new DataTable("tblOrder");
// Create
DataSet
DataSet
tblDataSet = new DataSet();
// Create
Columns and Add to Tables
tblCustomer.Columns.Add("ID", typeof(int));
tblCustomer.Columns.Add("CustomerName", typeof(string));
tblOrder.Columns.Add("ID", typeof(int));
tblOrder.Columns.Add("Order", typeof(string));
tblOrder.Columns.Add("CustomerID", typeof(int));
// Add
Test Data
tblCustomer.Rows.Add(1, "Bhaumik");
tblCustomer.Rows.Add(2, "Ramesh");
tblCustomer.Rows.Add(3, "Suresh");
tblOrder.Rows.Add(1, "Order1.1", 1);
tblOrder.Rows.Add(2, "Order1.2", 1);
tblOrder.Rows.Add(3, "Order1.3", 1);
tblOrder.Rows.Add(4, "Order2.1", 2);
tblOrder.Rows.Add(5, "Order3.1", 3);
tblOrder.Rows.Add(6, "Order3.2", 3);
// Add
Tables to DataSet
tblDataSet.Tables.Add(tblCustomer);
tblDataSet.Tables.Add(tblOrder);
// Create
Relation
tblDataSet.Relations.Add("CustOrderRelation",
tblCustomer.Columns["ID"], tblOrder.Columns["CustomerID"]);
BindingSource
bsCustomer = new BindingSource();
bsCustomer.DataSource = tblDataSet;
bsCustomer.DataMember = "tblCustomer";
BindingSource
bsOrder = new BindingSource();
bsOrder.DataSource = bsCustomer;
bsOrder.DataMember = "CustOrderRelation";
// Bind
Data to DataGridViews
dgvCustomer.DataSource =
bsCustomer;
dgvOrder.DataSource = bsOrder;
}
Demo: