Create a master/slave form with two Windows forms DataGridView controls

Source: Internet
Author: User

One of the most common scenarios for using the DataGridView control is the master/detail form, which displays a parent/child relationship between two database tables. Selecting a row in the primary table causes the detail table to be updated with the corresponding child data.

The Master/detail form is easy to implement, which requires the interaction between the DataGridView control and the BindingSource component. In this walkthrough, you will use two DataGridView controls and two BindingSource components to build a form. The form displays the two related tables in the Northwind SQL Server sample database:Customers and Orders. When you are finished, you will get a form that displays all the customers in the database in the main DataGridView and displays all orders for the selected customer in the details DataGridView .

Create a form

Create a master/detail form
  1. Creates a class derived from a Form that contains two DataGridView controls and two BindingSource components. The following code provides basic form initialization and contains a Main method. If you use Visual Studio Designer to create a form, you can use the designer-generated code instead of the code here, but be sure to use the name shown in the variable declaration here.

  2. Using System;Using System.Data;Using System.Data.SqlClient;Using System.Windows.Forms;
    PublicClass Form1:System.Windows.Forms.Form {Private DataGridView Masterdatagridview =New DataGridView ();Private BindingSource Masterbindingsource =New BindingSource ();Private DataGridView Detailsdatagridview =New DataGridView ();Private BindingSource Detailsbindingsource =New BindingSource ();
    [STAThreadAttribute ()]PublicStaticvoid Main () {Application.Run (New Form1 ()); }
    Initializes the form.Public Form1 () {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 (Form1_Load);         Span style= "Color:blue" >this. Text = "DataGridView master/detail demo";    }} / span>

  3. Implement a method in the form's class definition to handle details about the connection to the database. This example uses the GetData method to populate the DataSet object, add the DataRelation object to the dataset, and bind the BindingSource component. Be sure to set the connectionString variable to the value that applies to your database, and storing sensitive information, such as passwords, in the connection string may affect the security of your application. To control access to a database, a more secure approach is to use Windows authentication (also known as integrated security). For more information, see Securing Connection strings.

  4. Privatevoid GetData () {try {Specify a connection string. Replace the given value with aValid connection string for a Northwind SQL Server sampleDatabase accessible to your system. String connectionString ="Integrated Security=sspi; Persist Security info=false; "+"Initial catalog=northwind;data source=localhost"; 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 ("SELECT * from Customers", connection); Masterdataadapter.fill (data,"Customers");
    ADD data from the Orders table to the DataSet. SqlDataAdapter detailsdataadapter =New SqlDataAdapter ("SELECT * from Orders", connection); Detailsdataadapter.fill (data,"Orders");
    Establish a relationship between the tables. DataRelation relation =New DataRelation ("CustomersOrders", data. tables["Customers"]. columns["CustomerID"], data. tables["Orders"]. columns["CustomerID"]); Data. Relations.Add (relation);
    Bind the master Data connector to the Customers table.         Masterbindingsource.datasource = data; Masterbindingsource.datamember ="Customers";
    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.      &N bsp;  Detailsbindingsource.datasource = Masterbindingsource;         detailsbindingsource.datamember = " CustomersOrders ";    }     catch (SqlException)     {         MessageBox.Show (" ConnectionString variable with a connection string it is "+          & nbsp;  "valid for your system.");    }

  5. Implements a handler for the form's Load event that binds the DataGridView control to the BindingSource component and calls the GetData method. The following example includes code that adjusts the size of the DataGridView column to accommodate the displayed data.

  6. Privatevoid Form1_Load (Object sender, System.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 it columns automatically //adjust their widths when the data C     Hanges. Detailsdatagridview.autosizecolumnsmode = Datagridviewautosizecolumnsmode.allcells; }

Create a master/slave form with two Windows forms DataGridView controls

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.