问题:c#的数据库-DataRelation,现在一点头绪都没有,希望高手指点一下。
农叔叔 2005-01-24 03:16:04 在编译运行程序提示异常:
Customer ID:ALFKI
Order ID:10643
Order Date:1997-8-25 0:00:00
未处理的异常: System.NullReferenceException: 未将对象引用设置到对象的实例。
at usedb3.Main(String[] args) in f:\my work\c#\usedb3\usedb3\usedb3.cs:line 37
using System;
using System.Data;
using System.Data.SqlClient;
//namespace usedb3
//{
class usedb3
{
[STAThread]
static void Main(string[] args)
{
SqlConnection custConn=new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind;");
SqlDataAdapter custDA1=new SqlDataAdapter("select CustomerID,CompanyName from [Customers]",custConn);
SqlDataAdapter custDA2=new SqlDataAdapter("select OrderID,CustomerID,OrderDate from [Orders]",custConn);
SqlDataAdapter custDA3=new SqlDataAdapter("select OrderID,ProductID,Quantity from [Order Details]",custConn);
SqlDataAdapter custDA4=new SqlDataAdapter("select ProductID,ProductName from [Products]",custConn);
DataSet custDS=new DataSet();
custDA1.Fill(custDS,"Customers");
custDA2.Fill(custDS,"Orders");
custDA3.Fill(custDS,"OrderDetails");
custDA4.Fill(custDS,"Products");
//try
//{
foreach(DataRow custRow in custDS.Tables["Customers"].Rows)
{
Console.WriteLine("Customer ID:"+custRow["CustomerID"]);
DataRelation custOrderRel=custDS.Relations.Add("CustOrders",custDS.Tables["Customers"].Columns["CustomerID"],
custDS.Tables["Orders"].Columns["CustomerID"]);
foreach(DataRow orderRow in custRow.GetChildRows(custOrderRel))
{
Console.WriteLine(" Order ID:"+orderRow["OrderID"]);
Console.WriteLine("\tOrder Date:"+orderRow["OrderDate"]);
DataRelation orderDetailRel=new DataRelation("OrderDetails",custDS.Tables["Orders"].Columns["OrderID"],custDS.Tables["Order Details"].Columns["OrderID"]);
custDS.Relations.Add(orderDetailRel);
//是什么原因呢? 未处理的异常:System.NullReferenceException :未将对象引用设置到对象的实例
foreach(DataRow detailRow in orderRow.GetChildRows(orderDetailRel))
{
DataRelation orderProductRel=custDS.Relations.Add("OrderProducts",custDS.Tables["Products"].Columns["ProductID"],
custDS.Tables["Order Details"].Columns["ProductID"]);
Console.WriteLine("\t Product:"+detailRow.GetParentRow(orderProductRel)["ProductName"]);
Console.WriteLine("\t Quantity:"+detailRow["Quantity"]);
}
}
}
//}
//catch(System.NullReferenceException e)
//{
// Console.WriteLine("a0000000000System.NullReferenceException:");
//}
}
}
//}