DataSet ds = new DataSet();
DataTable table1 = new DataTable("tab1");
DataTable table2 = new DataTable("tab2");
DataTable table3 = new DataTable("tab3");
ds.Tables.Add(table1);
ds.Tables.Add(table2);
ds.Tables.Add(table3);
DataColumn dc1 = new DataColumn("a");
DataColumn dcc1 = new DataColumn("b");
DataColumn dc2 = new DataColumn("c");
DataColumn dcc2 = new DataColumn("d");
ds.Tables["tab1"].Columns.Add(dc1);
ds.Tables["tab1"].Columns.Add(dcc1);
ds.Tables["tab2"].Columns.Add(dc2);
ds.Tables["tab2"].Columns.Add(dcc2);
DataRow dr = ds.Tables["tab1"].NewRow();
dr["a"] = "1";
dr["b"] = "贺春林";
ds.Tables["tab1"].Rows.Add(dr);
DataRow drc = ds.Tables["tab2"].NewRow();
drc["c"] = "3";
drc["d"] = "我的地盘";
ds.Tables["tab2"].Rows.Add(drc);
DataRow dccc = ds.Tables["tab2"].NewRow();
dccc["c"] = "1";
dccc["d"] = "在在";
ds.Tables["tab2"].Rows.Add(dccc);
// Get the DataColumn objects from two DataTable objects in a DataSet.
DataColumn parentCol;
DataColumn childCol;
// Code to get the DataSet not shown here.
parentCol = ds.Tables["tab1"].Columns["a"];
childCol = ds.Tables["tab2"].Columns["c"];
// Create DataRelation.
DataRelation relCustOrder;
relCustOrder = new DataRelation("CustomersOrders", parentCol, childCol , true);
// Add the relation to the DataSet.
ds.Relations.Add(relCustOrder);以上是我写的测试代码,为什么会出错。错误信息为:
This constraint cannot be enabled as not all values have corresponding parent values. 
难道做两个DataSet里面的两个表关联时,一定要键值严格保持相等吗?有什么属性设置吗???
等待中....................在线....................................

解决方案 »

  1.   

    ds.Tables["tab1"].Columns["a"]; 跟 ds.Tables["tab2"].Columns["c"];的数据类型必须一致!DataColumn dc1 = new DataColumn("a",GetType("System.String"));
    DataColumn dc2 = new DataColumn("c",GetType("System.String"));
      

  2.   

    我改过来了呀,两边数据类型相同了,可还是不行啦。连接出错
    This constraint cannot be enabled as not all values have corresponding parent values. 急呀,,,,,,,,,,,等待中........................................
      

  3.   


    DataRow drc = ds.Tables["tab2"].NewRow();
    drc["c"] = "3";
    drc["d"] = "我的地盘";
    ds.Tables["tab2"].Rows.Add(drc);变为
    DataRow drc = ds.Tables["tab2"].NewRow();
    drc["c"] = "1";
    drc["d"] = "我的地盘";
    ds.Tables["tab2"].Rows.Add(drc);或者 再给table1加一行
    DataRow dr = ds.Tables["tab1"].NewRow();
    dr["a"] = "3";
    dr["b"] = "测试";
    ds.Tables["tab1"].Rows.Add(dr);
      

  4.   

    很明显
    "his constraint cannot be enabled as not all values have corresponding parent values."不是所有的关联值都存在父值你tab1 中的行数少于 tab2
    tab1中只有ID:1
    tab2中却有ID:1,3你要么在tab2中加一行ID为3的数据,要么把  parentCol, childCol 两个掉过来!
      

  5.   


      relCustOrder = new DataRelation("CustomersOrders", parentCol, childCol , true);
    变为
      relCustOrder = new DataRelation("CustomersOrders", parentCol, childCol , false);
      

  6.   

    liufuyahong 解决了。谢谢各位!!!!