本例用來顯示Northwind中的order details表中的數據交分組
1.建立一WinForm程序,並建立一數據庫連接,選擇order details表,此時會自動建立一個xsd的數據集類,如下圖
2.在項目中右鍵,新添加一個Report1.rdlc報表文件,並向此空白報表中添加一表格,如下圖
數據集屬性窗口中的“名稱”是此報表的名稱,在后面會用到,一定要記住。
以下為添加了表格的報表
3.從“報表數據”中把數據字段拖動到此表格中,行或列可以用右鍵“插入”功能即可。字段放好后,進行以orderid分組,
“行組”表示和字段顯示在同一行中,“列組“是專門起了一列。
4.給組頭及組尾中的相關屬性框進行表達式設計(雙擊字段或函數就會自動寫到表達式下)
給Quantity進行匯總,在其下面的對應的文本框中右鍵,設置其表達式
5.以下為設計好的報表
6.在Form1的窗體上放一reportViewer1,在Form1的load事件中寫入如下代碼:
private void Form1_Load(object sender, EventArgs e) { using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myconstr"].ConnectionString)) { SqlDataAdapter sda = new SqlDataAdapter("select * from [order details]", conn); conn.Open(); DataSet ds = new DataSet(); sda.Fill(ds, "Order Details");//表名為xsd中表的名稱 ReportDataSource RD = new ReportDataSource("DataSet1", ds.Tables[0]);//DataSet1為建立報表時用到的數據集名稱 this.reportViewer1.ProcessingMode=Microsoft.Reporting.WinForms.ProcessingMode.Local; this.reportViewer1.LocalReport.ReportPath=@"C:\Users\Administrator\Desktop\WindowsFormsApplication2\WindowsFormsApplication2\Report1.rdlc"; this.reportViewer1.LocalReport.DataSources.Clear(); this.reportViewer1.LocalReport.DataSources.Add(RD); this.reportViewer1.RefreshReport(); }
new ReportDataSource表示把現有的數據集和報表原來的數據集進行綁定
7.運行效果如下: