之前有介绍过在ActiveReports区域报表中如何根据数据源动态设置列以及列宽,动态设置报表中的列数量以及列宽度,本文中实现的需求是根据列的数量动态改变报表的纸张大小,以显示全部列信息。
首先,创建一个窗体,用户可以在该窗体中动态添加数据源的列数量,并可以指定那些咧会显示到报表中。
然后,创建一个区域报表模板,并在报表的后台代码中添加以下代码,以实现报表数据源与报表控件的绑定操作。
在报表的DataInitialize事件中初始化页面报表中的 Fields属性,Fields中添加的信息就是数据源中DataTable的列信息
private void SectionReport1_DataInitialize(object sender, EventArgs e){foreach (DataColumn col in dt.Columns){this.Fields.Add(col.ColumnName);
}}
在报表的ReportStart事件中设置报表纸张大小,报表控件及其Field属性以实现数据源绑定。
private void SectionReport1_ReportStart(object sender, EventArgs e){// 根据数据源调整报表纸张大小
this.PageSettings.Margins = new GrapeCity.ActiveReports.Document.Section.Margins(0.5f, 0.5f, 0.5f, 0.5f);this.PageSettings.DefaultPaperSize = false;this.PageSettings.PaperHeight = 12F;
this.PageSettings.PaperKind = System.Drawing.Printing.PaperKind.Custom;
this.PageSettings.PaperName = "自定义纸张";this.PageSettings.PaperWidth = dt.Columns.Count + 1.5f;
this.PrintWidth = this.PageSettings.PaperWidth - 1f;// 添加表头信息
GrapeCity.ActiveReports.SectionReportModel.Label lrow = new GrapeCity.ActiveReports.SectionReportModel.Label();
lrow.Name = "Header_Row";
lrow.Width = 0.5f;lrow.Location = new PointF(0, 0);
lrow.Text = "行号";
lrow.Border.BottomStyle = GrapeCity.ActiveReports.BorderLineStyle.ThickSolid;pageHeader.Controls.Add(lrow);GrapeCity.ActiveReports.SectionReportModel.TextBox trow = new GrapeCity.ActiveReports.SectionReportModel.TextBox();
trow.Name = "Detail_Row";
trow.Width = 0.5f;trow.Location = new PointF(0, 0);
trow.Border.BottomStyle = GrapeCity.ActiveReports.BorderLineStyle.Solid;trow.BackColor = Color.Teal;trow.Alignment = GrapeCity.ActiveReports.Document.Section.TextAlignment.Center;detail.Controls.Add(trow);for (int i = 0; i < dt.Columns.Count; i++){// 添加表头信息
GrapeCity.ActiveReports.SectionReportModel.Label label = new GrapeCity.ActiveReports.SectionReportModel.Label();
label.Name = string.Format("Header_{0}", i);label.Width = 1;label.Location = new PointF(i+0.5f, 0);
label.Text = dt.Columns[i].Caption;label.Border.BottomStyle = GrapeCity.ActiveReports.BorderLineStyle.ThickSolid;pageHeader.Controls.Add(label);// 添加明细信息
GrapeCity.ActiveReports.SectionReportModel.TextBox textBox = new GrapeCity.ActiveReports.SectionReportModel.TextBox();
textBox.Name = string.Format("Detail_{0}", i);textBox.Width = 1;textBox.Location = new PointF(i+0.5f, 0);
textBox.DataField = dt.Columns[i].Caption;textBox.Border.BottomStyle = GrapeCity.ActiveReports.BorderLineStyle.Solid;detail.Controls.Add(textBox);}}
在报表的 FetchData 事件中获取数据源数据,并设置给 Fields
private void SectionReport1_FetchData(object sender, FetchEventArgs eArgs){if (rowcount == dt.Rows.Count)
{// 如果是最后一行数据设置 EOF 为 true
eArgs.EOF = true;
return;
}else
{// 为数据字段设置数值
for (int i = 0; i < dt.Columns.Count; i++){this.Fields[dt.Columns[i].ColumnName].Value = dt.Rows[rowcount][i];
}// 设置行号
eArgs.EOF = false;
rowcount++;// 设置行号
(this.detail.Controls["Detail_Row"] as GrapeCity.ActiveReports.SectionReportModel.TextBox).Value = rowcount;}}
源码下载:VS2010 + ActiveReports 7