How To Display Parent and Child Fields Together in a DataGrid by Using Visual C# .NET (308454)



The information in this article applies to:

  • Microsoft Visual C# .NET (2003)
  • Microsoft Visual C# .NET (2002)

This article was previously published under Q308454
For a Microsoft Visual Basic .NET version of this article, see 308057.

This article refers to the following Microsoft .NET Framework Class Library namespace:
  • System.Data.SqlClient

IN THIS TASK

SUMMARY

This step-by-step article shows you how to display a DataGrid control that is populated with parent and child information from a relational dataset. As you move through the parent DataSet, you can click the plus sign (+) to the left of the DataGrid to view the related child records.

back to the top

Steps to Build the Sample

  1. Open Microsoft Visual Studio .NET, and create a new Visual C# Windows Application project.
  2. Use the toolbox to add a Button control and a DataGrid control to the default form.
  3. In the Properties window, change the Text property of the button to Load.
  4. Double-click Load to add an event handler.
  5. Add the following code to the top of the Code window:
    using System.Data.SqlClient;
    					
  6. Add the following code to the Button1_Click event handler:
    SqlConnection con = new SqlConnection("server=haroldo2;uid=sa;"  + 
                                          "pwd=Password1;database=northwind");
    SqlDataAdapter daCust = new SqlDataAdapter("Select * From Customers Where CustomerID Like 'A%'", con);
    SqlDataAdapter daOrders = new SqlDataAdapter("Select * From Orders Where CustomerID Like 'A%'", con);
    DataSet ds = new DataSet();
    daCust.Fill(ds, "Cust");
    daOrders.Fill(ds, "Orders");
    //Creates the relationship.
    ds.Relations.Add("CustOrd", ds.Tables["Cust"].Columns["CustomerID"], 
                                ds.Tables["Orders"].Columns["CustomerID"]);
    dataGrid1.DataSource = ds;
    dataGrid1.DataMember = "Cust";
    					
  7. Modify the SqlConnection string to point to a valid Microsoft SQL Server database.
  8. Press the F5 key to compile and run the application.
  9. Notice that the grid is empty initially. Click Load to populate the grid.
  10. Click the plus sign (+) to display the links to the child records. In this example, one child relation appears. Click the relation to display the child records.
  11. In the upper right corner of the grid, click the back arrow to return to the parent records.
back to the top

Modification Type:MinorLast Reviewed:7/15/2004
Keywords:kbCtrl kbHOWTOmaster KB308454 kbAudDeveloper