DataAdapter dataAdapter = DataAdapter.Current;
// I am passing the SQL statement and the table name to my database which knows the ConnectionString within the LoadData function
DataTable dt0 = dataAdapter.LoadData("select Id, c_Name from `country`", "country");
if (dt0 != null) {
dgrData.DataSource = dt0;
}
var f = new ReportForm();
f.ReportColumns = this.dataGridView1.Columns.Cast<DataGridViewColumn>()
.Select(x => new ReportColumn(x.DataPropertyName)
{ Title = x.HeaderText, Width = x.Width }).ToList();
f.ReportData = this.dataGridView1.DataSource;
f.ShowDialog();
using System;
using System.Drawing;
public class ReportColumn
public ReportColumn(string name)
Name = name;
Title = name;
Type = typeof(System.String);
Width = GetPixelFromInch(1);
Expression = string.Format("=Fields!{0}.Value", name);
HeaderBackColor = Color.LightGray;
public string Name { get; set; }
public string Title { get; set; }
public Type Type { get; set; }
public int Width { get; set; }
public float WidthInInch
get { return GetInchFromPixel(Width); }
public string Expression { get; set; }
public Color HeaderBackColor { get; set; }
public string HeaderBackColorInHtml
get { return ColorTranslator.ToHtml(HeaderBackColor); }
private int GetPixelFromInch(float inch)
using (var g = Graphics.FromHwnd(IntPtr.Zero))
return (int)(g.DpiY * inch);
private float GetInchFromPixel(int pixel)
using (var g = Graphics.FromHwnd(IntPtr.Zero))
return (float)pixel / g.DpiY;
}
向项目中添加一个
Form
,并将一个
ReportViewer
控件添加到表单中,并将此代码放入类中:
public partial class ReportForm : Form
public ReportForm()
InitializeComponent();
ReportColumns = new List<ReportColumn>();
this.Load+=new EventHandler(ReportForm_Load);
public List<ReportColumn> ReportColumns { get; set; }
public Object ReportData { get; set; }
private void ReportForm_Load(object sender, EventArgs e)
var report = new DynamicReport();
report.Session = new Dictionary<string, object>();
report.Session["Model"] = this.ReportColumns;
report.Initialize();
var rds = new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", this.ReportData);
this.reportViewer1.LocalReport.DataSources.Clear();
this.reportViewer1.LocalReport.DataSources.Add(rds);
var reportContent = System.Text.Encoding.UTF8.GetBytes(report.TransformText());
using (var stream = new System.IO.MemoryStream(reportContent))