在C#中设置主从表有以下几个重点:
1.设置表之间的关系 DataRelation
2.设置主从表的数据源 BindingSource
关键是设计从表的数据源应为主表的数据源,它的DataMember应为主从表关系的名称
以下为运行时的截图,界面上有两个datagridview
代码(全在Form1构造函数中实现):
public Form1()
{
InitializeComponent();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=.;Initial Catalog=Northwind;Integrated Security=True";
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter sdaMaster = new SqlDataAdapter("Select * from Orders", conn);
sdaMaster.Fill(ds, "Orders");
SqlDataAdapter sdaDetail = new SqlDataAdapter("select * from [Order Details]", conn);
sdaDetail.Fill(ds, "OrderDetails");
//创建两个表之间的关系
DataRelation dr=new DataRelation("FK_Orders_OrderDetails",ds.Tables["Orders"].Columns["OrderID"],ds.Tables["OrderDetails"].Columns["OrderID"]);
ds.Relations.Add(dr);
//以下为创建数据源
BindingSource bsMaster = new BindingSource();
bsMaster.DataSource = ds.Tables[0].DefaultView;
// bsMaster.DataMember = "Orders";
BindingSource bsDetail = new BindingSource();
bsDetail.DataSource = bsMaster; //从表的数据源应该设置为主表的BindingSource
bsDetail.DataMember = "FK_Orders_OrderDetails"; //从表的主从关系名
dgvMaster.DataSource = bsMaster;
dgvDetail.DataSource = bsDetail;
}
}