.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
abhays
Clintonzz
arronlee
cathyhill345
mattyclown

Home >> Articles >> Windows Application >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Show Master Detail records with DataGridView

Posted By:Ravi Ranjan Kumar       Posted Date: July 31, 2011    Points: 200    Category: Windows Application    URL: http://raviranjankr.wordpress.com/  

This article help you to learn how to create master details with DatagridView using C# for Windows Application.
 

Introduction

The Concept of MasterDetails is came in existence for displaying Details using DataGridView.  Its used to display Data from multiple table based on condition just like Joining. Suppose a user have two table named X and Y. and user need to display all details from Table Y based on selecting value of table X. then in this Condition using  MasterDetails can be useful. 
The DataGridView does not provide any new features apart from virtual mode to enable this.

How to Create MasterDetails 

The DataGridView does not provide any new features apart from virtual mode to enable this
DataGridView control can be one of the most common scenarios for MasterDetails form  in which a parent/child relationship between two database tables is displayed. Selecting rows in the master table causes the detail table to update with the corresponding child data.
Implementing a master/detail form is easy using the interaction between the DataGridView control and the BindingSource component.
The below sample will show two related tables in the AdventureWorks SQL Server Sample database: HumanResources.Department and HumanResources.EmployeeDepartmentHistory. 
By selecting a customer in the master DataGridView all the orders for the customer will appear in the detail DataGridView.


It's better to create a user Control which will responsible to display itself as a MasterDetails embedding two DataGridView one for parent Details as well another for child details.

Code for User Control for Master Details 


Complete code will be
class DataGridMasterDetails:UserControl
    {
        string ConnectionString;
        string Query1;
        string Table1;
        string Query2;
        string Table2;
        string RelationName;
        string CommonColumn;

        public DataGridMasterDetails(string connectionstring, string query1, string table1, string query2, string table2, string relationname, string commoncolumn)
        {
            masterDataGridView.Dock = DockStyle.Fill;
            detailsDataGridView.Dock = DockStyle.Fill;
            SplitContainer splitContainer1 = new SplitContainer();
            splitContainer1.Dock = DockStyle.Fill;
            splitContainer1.Orientation = Orientation.Horizontal;
            splitContainer1.Panel1.Controls.Add(masterDataGridView);
            splitContainer1.Panel2.Controls.Add(detailsDataGridView);
            this.Controls.Add(splitContainer1);
            this.Load += new System.EventHandler(DataGridMasterDetails_Load);
           
            ConnectionString = connectionstring;
            Query1 = query1;
            Query2 = query2;
            Table1 = table1;
            Table2 = table2;
            RelationName = relationname;
            CommonColumn = commoncolumn;
        }

        private DataGridView masterDataGridView = new DataGridView();
        private BindingSource masterBindingSource = new BindingSource();
        private DataGridView detailsDataGridView = new DataGridView();
        private BindingSource detailsBindingSource = new BindingSource();

        public void DataGridMasterDetails_Load(object sender,EventArgs e)
        {
            // Bind the DataGridView controls to the BindingSource
            // components and load the data from the database.
            masterDataGridView.DataSource = masterBindingSource;
            detailsDataGridView.DataSource = detailsBindingSource;
            GetData();
            // Resize the master DataGridView columns to fit the newly loaded data.
            masterDataGridView.AutoResizeColumns();
            // Configure the details DataGridView so that its columns automatically
            // adjust their widths when the data changes.
            detailsDataGridView.AutoSizeColumnsMode =
            DataGridViewAutoSizeColumnsMode.AllCells;
        }
        public void GetData()
        {
            try
            {
                // Specify a connection string. Replace the given value with a
                // valid connection string for a Northwind SQL Server sample
                // database accessible to your system.

                

                SqlConnection connection = new SqlConnection(ConnectionString);

                // Create a DataSet.
                DataSet data = new DataSet();
                data.Locale = System.Globalization.CultureInfo.InvariantCulture;

                // Add data from the Customers table to the DataSet.
                SqlDataAdapter masterDataAdapter = new
                SqlDataAdapter(Query1, connection);
                masterDataAdapter.Fill(data, Table1);

                // Add data from the Orders table to the DataSet.
                SqlDataAdapter detailsDataAdapter = new
                SqlDataAdapter(Query2, connection);
                detailsDataAdapter.Fill(data, Table2);

                // Establish a relationship between the two tables.
                DataRelation relation = new DataRelation(RelationName,
                data.Tables[Table1].Columns[CommonColumn],
                data.Tables[Table2].Columns[CommonColumn]);
                data.Relations.Add(relation);

                // Bind the master data connector to the Customers table.
                masterBindingSource.DataSource = data;
                masterBindingSource.DataMember = Table1;

                // Bind the details data connector to the master data connector, using the DataRelation name to filter the information in the
                // details table based on the current row in the master table.
                detailsBindingSource.DataSource = masterBindingSource;
                detailsBindingSource.DataMember = RelationName;
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }
Take a look how to call  DataGridMasterDetails  At Load event of Form for displaying MasterDetails



Complete source code will be 

private void Form1_Load(object sender, EventArgs e)
        {

            string constring = "Data Source =.;Initial Catalog =AdventureWorks;uid =sa; pwd = YourPassword";
            string Query1 = "select * from HumanResources.Department";
            string Query2 = "select * from HumanResources.EmployeeDepartmentHistory";
            string tablename1 = "HumanResources.Department";
            string tablename2 = "HumanResources.EmployeeDepartmentHistory";
            string CommonColumn = "DepartmentID";
            
            DataGridMasterDetails obj = new DataGridMasterDetails
                (constring, Query1, tablename1,
                Query2, tablename2,
                "CombindedDetails",CommonColumn);
            obj.Dock = DockStyle.Fill;
            //  obj.Show();
            this.Controls.Add(obj);
        }
Now Compile application. after compilation it will be resemble as 


How it works

Take a look at below animated image which will help you to understand its way of working 


For Getting more details you can Download Source Code.


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend