问题:c#的数据库-DataRelation,现在一点头绪都没有,希望高手指点一下。

农叔叔 农叔叔 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
在编译运行程序提示异常:
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:");
//}
}
}
//}
...全文
评论 4
收藏 已收藏
分享
返回顶部
农叔叔
C# 111,128 成员 642,536 内容