我用两个DataGridView来显示主从表的数据,但是当查询出来的主表没有数据时就出错。代码如下
DataSet ds = GetData();
ds.Relations.Add ( "EmployeesInfo" , ds.Tables [ "dsTable" ].Columns [ "LoanBh" ] ,
[align=left]ds.Tables [ "dsTable1" ].Columns [ "LoanBh" ] );
BindingSource masterBindingSource = new BindingSource ( );
BindingSource detailsBindingSource = new BindingSource ( );
masterBindingSource.DataSource = ds;
masterBindingSource.DataMember = "dsTable";
detailsBindingSource.DataSource = masterBindingSource;
detailsBindingSource.DataMember = "EmployeesInfo";
this.dgvMaster.DataSource = masterBindingSource;
this.dgvDetails.DataSource = detailsBindingSource;[/align]
当ds.Tables [ "dsTable" ]中没有数据时捕捉到 System.ArgumentException
Message="不能启用此约束,因为不是所有的值都具有相应的父值。"的异常;
这时ds.Tables [ "dsTable1" ]是有数据的(从表是查询出所有的数据,根据Relations现实选中对应主表的从表信息)。只是对应不到主表!
问题:1:目前这种方式怎么解决这个问题?
问题:2:这种显示主从表数据的方式对不对?
DataSet ds = GetData();
ds.Relations.Add ( "EmployeesInfo" , ds.Tables [ "dsTable" ].Columns [ "LoanBh" ] ,
[align=left]ds.Tables [ "dsTable1" ].Columns [ "LoanBh" ] );
BindingSource masterBindingSource = new BindingSource ( );
BindingSource detailsBindingSource = new BindingSource ( );
masterBindingSource.DataSource = ds;
masterBindingSource.DataMember = "dsTable";
detailsBindingSource.DataSource = masterBindingSource;
detailsBindingSource.DataMember = "EmployeesInfo";
this.dgvMaster.DataSource = masterBindingSource;
this.dgvDetails.DataSource = detailsBindingSource;[/align]
当ds.Tables [ "dsTable" ]中没有数据时捕捉到 System.ArgumentException
Message="不能启用此约束,因为不是所有的值都具有相应的父值。"的异常;
这时ds.Tables [ "dsTable1" ]是有数据的(从表是查询出所有的数据,根据Relations现实选中对应主表的从表信息)。只是对应不到主表!
问题:1:目前这种方式怎么解决这个问题?
问题:2:这种显示主从表数据的方式对不对?
select * from 子表
同一个SQL语句里面! 然后返回dataset 数据的时候! ds.tables[0]主表 ds.tables[1]子表...
ds.Relations.Add (relation);
还有没有别的什么解决方法?
难道只能点一下主表记录取它的ID在去从表查询数据再绑定么?
“不能启用此约束,因为不是所有的值都具有相应的父值”这中错误!
select @COUNT = count(*) from 主 where 查询条件
if(@COUNT >0 )
begion
select * from 主 where 查询条件
select * from 子 where 查询条件
end这样不就可以吗?
也还有其他别的办法!你可以在想想!
第一种: if ( ds.Tables [ "dsTable" ].Rows.Count == 0 )
{
ds.Tables [ "dsTable1" ].Clear ( );
}第二种:在查询是用一条不可能的去查询从表,从而复制从表结构,
经测试这两种方法都可以。
当然就无奈的做法就是先查询主表,再在点击事件里获取主表的ID后查询从表,然后各自绑定。目前这种做法就免去了这些步骤。问题解决,谢谢各位的热心!