我找到了如何将数据表绑定到reportviewer的答案,我将在这里分享可能对其他人有用。
- 添加到表单clsTables 类、Report1.rdlc 文件、reportViewer1。
- 然后点击reportViewer1的右上角,设置选择报告为Test.Report1.rdlc。
- 在 Report1.rdlc 上
- 点击新建,
- 添加数据集名称:dsBody
数据源:测试
可用数据集:clsTables
- 点击确定
- 右键单击 Report1.rdlc 选择Insert Table,将 dsBody 元素( Column0, Colum1, Column2 )拖到 Report1.rdlc table 中。
Namespace Test{
public class clsTables {
// constructor
public clsTables(string col0, string col1, string col2) {
this.Column0= col0;
this.Column1= col1;
this.Column2= col2;
}
// properties
public string Column0{ get; set; }
public string Column1{ get; set; }
public string Column2{ get; set; }
}
}
namespace Test{
public class clsMain{
public void BindToRepprtViewer() {
// create dataset
DataSet ds = new DataSet("myDataset");
// create datatable
DataTable dt = new DataTable("myDatatable");
// add columns
dt.Columns.Add("column1", typeof(string));
dt.Columns.Add("column2", typeof(string));
dt.Columns.Add("column3", typeof(string));
// insert data rows
dt.Rows.Add("row1-col1", "row1-col2", "row1-col3");
dt.Rows.Add("row2-col1", "row2-col2", "row2-col3");
// add datatable to dataset
ds.Tables.Add(dt);
// save rows to rowList
List<clsTables> rowList = new List<clsTables>();
rowList .Clear();
foreach (DataRow row in dt.Rows) {
rList.Add(new clsTables(Convert.ToInt32(row.ItemArray[0]), row.ItemArray[1].ToString(), row.ItemArray[2].ToString()));
}
// binding rowList to bs
BindingSource bs = new BindingSource();
bs.DataSource = rowList;
// binding bs to rds
ReportDataSource rds = new ReportDataSource();
rds.Name = "dsBody";
rds.Value = bs;
// binding rds to report viewer
reportViewer1.Reset();
reportViewer1.LocalReport.ReportEmbeddedResource = "Test.Report1.rdlc";
reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(rds);
reportViewer1.RefreshReport();
}
}
}