表之间的父子关系的C#代码错误 [英] Error in C# Code for Parent-child Relationship between tables

查看:118
本文介绍了表之间的父子关系的C#代码错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码用于设置2个表之间的父子关系,并通过2个dataGridViews显示.

Below code is used to set Parent-child relationship between 2 tables and display through 2 dataGridViews.

using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS; database= NORTHWND; Persist Security Info=false; Integrated Security=true;"))
            {
                SqlCommand cmd1 = new SqlCommand();
                SqlCommand cmd2 = new SqlCommand(); 
                cmd1 = con.CreateCommand();
                cmd2 = con.CreateCommand();
                cmd1.CommandText = "Select * from Customers";
                cmd2.CommandText = "Select * from Orders";
                cmd1.Connection = con;
                cmd2.Connection = con;

                con.Open();
                    SqlDataAdapter adp1 = new SqlDataAdapter(cmd1);
                    DataSet ds = new DataSet();
                    adp1.Fill(ds, "Customers");
                    SqlDataAdapter adp2 = new SqlDataAdapter(cmd2); 
                    adp2.Fill(ds, "Orders");
                DataRelation relation = new DataRelation("CustomersOrders", 
                    ds.Tables["Customers"].Columns["CustomerID"], 
                    ds.Tables["Orders"].Columns["CustomerID"]); 
                    ds.Relations.Add(relation);  // add relation 
                    dataGridView1.DataSource = ds; 
                    dataGridView1.DataMember = "Customers";
                    dataGridView2.DataSource = ds; 
                    dataGridView2.DataMember = "CustomersOrders"; // this line shows error 
            }



对于最后一行代码,代码在执行时显示以下错误消息:
无法创建"CustomerOrders"字段的子列表."
原因是什么,应该怎么解决?



Code shows following error message on execution, for the last line of code:
"Childlist for field "CustomerOrders" can’t be created."
What is the reason and what should be the solution?

推荐答案


您是否尝试将DataMember 设置为"Customers.CustomersOrders".据我所知,这是正确的语法.
问候
Hi,
Have you tried setting the DataMember to "Customers.CustomersOrders". As far as I know that''s the correct syntax.
Regards


如果您正在调试并且同时打开了数据库,也会发生这种情况.
This can also happen if you''re debugging and you have the DB open at the same time.


请参见
See Here[^] it may help


这篇关于表之间的父子关系的C#代码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆