效果
xtrareport 布局
From 代码
private DataSet Getdata() { DataSet ds = new DataSet(); //config配置字符串 string constr=ConfigurationManager.ConnectionStrings["constr"].ToString(); SqlConnection mycon = new SqlConnection(constr); try { mycon.Open(); //表1 SqlCommand mycom = new SqlCommand("select * from dp ", mycon); SqlDataAdapter dpt = new SqlDataAdapter(mycom); dpt.Fill(ds, "dp"); //表2 SqlCommand mycom2 = new SqlCommand("select * from duser ", mycon); dpt = new SqlDataAdapter(mycom2); dpt.Fill(ds, "duser"); mycon.Close(); //创建主外键 DataColumn parent = ds.Tables["dp"].Columns["dpid"]; DataColumn child = ds.Tables["duser"].Columns["dpid"]; //添加关系并指定为RelationColumn DataRelation rel = new DataRelation("RelationColumn", parent, child); ds.Relations.Add(rel); } catch (Exception ex) { MessageBox.Show(ex.Message); } return ds; } private void simpleButton1_Click(object sender, EventArgs e) { DataSet ds=Getdata(); XtraReport1 report = new XtraReport1(ds); report.Landscape = true; documentViewer1.DocumentSource = report; report.CreateDocument(); } }
Xtrareport 代码
public XtraReport1(DataSet ds) { InitializeComponent(); //绑定主表 this.DataSource = ds; this.DataMember = "dp"; this.xrTableCell1.DataBindings.Add("Text", ds, "dp.dpname"); //指定从表成员 DetailReport.DataMember = "RelationColumn"; //绑定从表 DetailReport.DataSource = ds; this.xrTableCell2.DataBindings.Add("Text", ds, "RelationColumn.userid"); this.xrTableCell3.DataBindings.Add("Text", ds, "RelationColumn.username"); }
注意事项
dataset数据集中绑定了两个表,一定要看清楚有没有填充进去,没有填充的话,从表不会显示数据的