Many developers finding a way how to show Parent child records in windows form like ms access show like expand and collapse records .In this article I am going to teach you that same thing how show such records in hierarchical view .
ADO.NET 2.0/3.5, Window Forms.
Knowledge of ADO.NET and knowledge of basic Database connectivity.
Now you have seen the above screen shot and knowing what we are going to build which is something similar to ms access's Data Display. So let's get started!
First of all we need to create 2 Sample Table for whose data we are going to display onto our form !!
In application make Two Tables for instance:
Here in User Data Table Is master table while User Detail Table is Child Table.
Now we are gonna use some old stuff here that is DataGrid Control. Because dataGridView Control is not supporting the hierarchical view of data, so let's add DataGrid Control to your tool box by Right Click in tool Box >>Choose Items
And Choose Data Grid there:
Now Click OK.
You will have new Control Called DataGrid in your Tool Box Drag and Drop it on the Form like normal DataGridView.
Now do connectivity Like below :
Everything in code I have mentioned by comment what it does! so you can understand it easily.
General steps I have done in code:
Connect to Database.
Fill DataTable(master) with Data.
Fill DataTable(child) with data.
Add Both to Dataset.
Build A relation between them in memory.
Band it to DataGrid Control.
public partial class Form1 : Form
private void Form1_Load(object sender, EventArgs e)
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand comm = new SqlCommand("select * from UserData",con);
DataTable master = new DataTable();
DataTable child = new DataTable();
// Fill Table 2 with Data
SqlDataAdapter da = new SqlDataAdapter(comm);
// Fill Table1 with data
comm = new SqlCommand("select * from UserDetail",con);
DataSet ds = new DataSet();
//Add two DataTables in Dataset
// Create a Relation in Memory
DataRelation relation = new DataRelation("",ds.Tables.Columns,ds.Tables.Columns,true);
// Set DataSource
dataGrid1.DataSource = ds.Tables;
F5 to run project! and you can now collapse and expands records in Hierarchical View.
That's it! You have achieved what you wanted! without using any third party controls.
Though now days in there are many vendors that provide better Hierarchical view Data Controls than this old DataGrid Control like major vendors are devExpress , Telerik RAD controls etc, that can provide better feature than, many more options also for data binding .
This article teaches about how to showing parent/child relationship between two table records in single grid view.