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:
IN THIS TASKSUMMARY
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- Open Microsoft Visual Studio .NET, and create a new Visual C# Windows Application project.
- Use the toolbox to add a Button control and a DataGrid control to the default form.
- In the Properties window, change the Text property of the button to Load.
- Double-click Load to add an event handler.
- Add the following code to the top of the Code window:
using System.Data.SqlClient;
- 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";
- Modify the SqlConnection string to point to a valid Microsoft SQL Server database.
- Press the F5 key to compile and run the application.
- Notice that the grid is empty initially. Click Load to populate the grid.
- 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.
- In the upper right corner of the grid, click the back arrow to return to the parent records.
back to the top
Modification Type: | Minor | Last Reviewed: | 7/15/2004 |
---|
Keywords: | kbCtrl kbHOWTOmaster KB308454 kbAudDeveloper |
---|
|