Exceptions: System.NullReferenceException while trying to create relation between tables in dataSet
使用C#、. net Framework 4.5,VS 2012
尝试在数据集中的表之间创建简单关系,但是遇到System.NullReferenceException,正如我在MSDN上看到的那样,它的意思是
我的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | //create place for storing all tables from data base private DataSet myDS = new DataSet("AutoLot"); //command builders for easy way access to tables private SqlCommandBuilder sqlCInventory; private SqlCommandBuilder sqlCOrders; private SqlCommandBuilder sqlCCustomers; //adapters for each table private SqlDataAdapter sqlAInventory; private SqlDataAdapter sqlAOrders; private SqlDataAdapter sqlACustomers; //connection string private string cnStr = string.Empty; public MainForm() { InitializeComponent(); //get connection string from .config file cnStr = ConfigurationManager.ConnectionStrings["AutoLotSqlProvider"].ConnectionString; //create adapters sqlACustomers = new SqlDataAdapter("Select * From Customers", cnStr); sqlAInventory = new SqlDataAdapter("Select * From Inventory", cnStr); sqlAOrders = new SqlDataAdapter("Select * From Orders", cnStr); //automatic generate commands sqlCCustomers = new SqlCommandBuilder(sqlACustomers); sqlCInventory = new SqlCommandBuilder(sqlAInventory); sqlCOrders = new SqlCommandBuilder(sqlAOrders); //add table to data Set sqlAInventory.Fill(myDS); sqlAOrders.Fill(myDS); sqlACustomers.Fill(myDS); //create relationship between tables BuildTableRelationShip(); //create DataSourse for datGrids on UI dataGridViewCustomer.DataSource = myDS.Tables["Inventory"]; dataGridViewOrders.DataSource = myDS.Tables["Orders"]; dataGridViewCustomer.DataSource = myDS.Tables["Customers"]; } |
这是我的例外
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | private void BuildTableRelationShip() { //create object of relationShips DataRelation dr = new DataRelation("CustomersOrders", //name of relation myDS.Tables["Customers"].Columns["CustID"], //main columns myDS.Tables["Orders"].Columns["OrderID"]); //related columns myDS.Relations.Add(dr); //second relation dr = new DataRelation("InventoryOrder", myDS.Tables["Inventory"].Columns["CarID"], myDS.Tables["Orders"].Columns["OrderID"]); //add relations to dataset myDS.Relations.Add(dr); } |
为什么我收到此Null参考异常? 我想念什么?
编辑
您应该在单个
1 2 3 | sqlAInventory.Fill(myDS); sqlAOrders.Fill(myDS); sqlACustomers.Fill(myDS); |
会成为
1 2 3 | sqlAInventory.Fill(myDS,"Inventory"); sqlAOrders.Fill(myDS,"Orders"); sqlACustomers.Fill(myDS,"Customers"); |
如果该表不存在,此方法将自动将其添加到您的