簡體   English   中英

C#2015 Winform Datagrid視圖將選定的行添加到rdlc報表

[英]C# 2015 winform datagrid view selected rows to rdlc report

我是Windows應用程序和C#的新手。 我將C# 2015用於具有MS-Access 2007數據庫的windows application

我已經完成了使用表單的CRUD操作並在datagridview顯示記錄,似乎工作正常。

現在,我想要的是將選定的gridview rows顯示到報告中並進行打印。 我也不希望它們顯示為表格,而是每個記錄的表格。 這樣,如果選擇了3行,則每行將打印3頁。

我完成的代碼如下:

customer.cs

namespace bolt
{
    class customer
    {
        public int? id { get; set; }
        public string firstName { get; set; }
        public string middleName { get; set; }
        public string lastName { get; set; }
        public string panNo { get; set; }
        public string email { get; set; }
        public string mobile { get; set; }
        public string address { get; set; }
        public int dptype { get; set; }
        public string benificiaryId { get; set; }
        public string bankName { get; set; }
        public string bankBranch { get; set; }
        public string bankAccountNo { get; set; }

        customer(int? id = null, string firstName = null, string middleName = null, string lastName = null,
            string panNo = null, string email = null, string mobile = null, string address = null, int dptype = 1,
            string benificiaryId = null, string bankName = null, string bankBranch = null, string bankAccountNo = null
            )
        {
            this.id = null;
            this.firstName = firstName;
            this.middleName = middleName;
            this.lastName = lastName;
            this.panNo = panNo;
            this.email = email;
            this.mobile = mobile;
            this.address = address;
            this.dptype = dptype;
            this.benificiaryId = benificiaryId;
            this.bankName = bankName;
            this.bankBranch = bankBranch;
            this.bankAccountNo = bankAccountNo;
        }

        public customer()
        {
        }
    }
}

在其中添加了一個表格frmReportreportviewer

添加了一個表格frmCustomer ,其中包含datagridview

添加了一個rdlc報告rptBolt.rdlc ,我沒有在其中添加任何控件。

frmCustomer ,我有一個打印按鈕。 在點擊它下面的代碼

private void btnPrint_Click(object sender, EventArgs e)
{
    List<customer> lstCustomer = new List<customer>();


    foreach(DataGridViewRow row in dgCustomers.SelectedRows)
    {
        customer c = new customer();
        c.id = Convert.ToInt32(row.Cells[dgCustomers.Columns["Id"].Index].Value);

        lstCustomer.Add(c);
    }

    frmReport r = new frmReport();
    r.Show();
    ReportViewer v = r.Controls.Find("reportViewer1", true).FirstOrDefault() as ReportViewer;
    ReportDataSource dataset = new ReportDataSource("boltReport", lstCustomer);
    v.LocalReport.ReportEmbeddedResource = "bolt.rptBolt.rdlc";
    v.LocalReport.DataSources.Clear();
    v.LocalReport.DataSources.Add(dataset);
    v.LocalReport.Refresh();
    dataset.Value = lstCustomer;

    v.LocalReport.Refresh();

    this.Hide();
}

我已經扔了很多教程,但是每個教程都使用直接連接到數據庫的報表向導和數據集,就我而言,我使用的是列表。

讓我知道我是在錯誤的道路上還是應該做什么? 您可以提供答案,或者至少提供一個我可以得到我想要的鏈接。

不需要所有這些代碼,您只需在目標表或select語句中添加一列並為其分配值即可,例如RSelected =1只需將更新值保存為Re,將Re selected設置為1,然后必須將其分配為0或您需要的值,那么您可以在SQL語句的代碼中選擇該值))))))

您是否要將類似“ Select * From TableName”的查詢結果傳遞到DataTable objetc中,以傳遞給ReportViewer?

您必須執行以下操作:

  1. 創建一個新的rdlc文件,其中至少包含一個Tablix對象
  2. 確保新的rdlc文件的“構建操作”屬性設置為“內容”,並將“復制到輸出目錄”設置為“始終復制”
  3. 創建接收查詢的方法

查看此處創建的方法

  1. 創建方法以接收查詢填充的DataTable對象

     /// Method that return a new Tablix formatted for our file Report_Dynamic.rdlc /// </summary> /// <param name="datos">DataTable complete from Select statement</param> /// <returns>New Tablix with all columns and rows from your DataTable ☺</returns> private string CrearTablaDeReporteXML(DataTable datos) { StringBuilder sb = new StringBuilder(); sb.AppendLine("<Tablix Name='Tablix1'>"); #region TablixBody sb.AppendLine(" <TablixBody>"); #region Tablixcolumns sb.AppendLine(" <TablixColumns>"); for (int i = 0; i < datos.Columns.Count; i++) { //Columns sb.AppendLine(" <TablixColumn>"); sb.AppendLine(" <Width>1.06in</Width>"); sb.AppendLine(" </TablixColumn>"); } sb.AppendLine(" </TablixColumns>"); #endregion #region TablixRows sb.AppendLine(" <TablixRows>"); #region Row header sb.AppendLine("<TablixRow>"); sb.AppendLine("<Height>0.25in</Height>"); sb.AppendLine("<TablixCells>"); int numeroTexto = 1000; for (int i = 0; i < datos.Columns.Count; i++) { sb.AppendLine("<TablixCell>"); sb.AppendLine("<CellContents>"); sb.AppendLine(string.Format("<Textbox Name='Textbox{0}'><CanGrow>true</CanGrow><KeepTogether>true</KeepTogether><Paragraphs><Paragraph><TextRuns><TextRun><Value>{1}</Value><Style><FontSize>8pt</FontSize><FontWeight>Bold</FontWeight></Style></TextRun></TextRuns><Style/></Paragraph></Paragraphs><rd:DefaultName>Textbox1</rd:DefaultName><Style><Border><Color>LightGrey</Color><Style>Solid</Style></Border><BackgroundColor>LightGrey</BackgroundColor><PaddingLeft>2pt</PaddingLeft><PaddingRight>2pt</PaddingRight><PaddingTop>2pt</PaddingTop><PaddingBottom>2pt</PaddingBottom></Style></Textbox>", numeroTexto, datos.Columns[i])); sb.AppendLine("</CellContents>"); sb.AppendLine("</TablixCell>"); numeroTexto++; } sb.AppendLine("</TablixCells>"); sb.AppendLine("</TablixRow>"); #endregion #endregion for (int i = 0; i < datos.Rows.Count; i++) { //Rows sb.AppendLine(" <TablixRow>"); sb.AppendLine(" <Height>0.25in</Height>"); sb.AppendLine(" <TablixCells>"); for (int j = 0; j < datos.Columns.Count; j++) { sb.AppendLine(" <TablixCell>"); sb.AppendLine(" <CellContents>"); sb.AppendLine(string.Format(" <Textbox Name='Textbox{0}'><CanGrow>true</CanGrow><KeepTogether>true</KeepTogether><Paragraphs><Paragraph><TextRuns><TextRun><Value>{1}</Value><Style><FontSize>8pt</FontSize></Style></TextRun></TextRuns><Style/></Paragraph></Paragraphs><rd:DefaultName>Textbox2</rd:DefaultName><Style><Border><Color>LightGrey</Color><Style>Solid</Style></Border><PaddingLeft>2pt</PaddingLeft><PaddingRight>2pt</PaddingRight><PaddingTop>2pt</PaddingTop><PaddingBottom>2pt</PaddingBottom></Style></Textbox>", numeroTexto, datos.Rows[i].ItemArray[j].ToString().Replace("&", ""))); sb.AppendLine(" </CellContents>"); sb.AppendLine(" </TablixCell>"); numeroTexto++; } sb.AppendLine(" </TablixCells>"); sb.AppendLine(" </TablixRow>"); } sb.AppendLine(" </TablixRows>"); sb.AppendLine(" </TablixBody>"); #endregion sb.AppendLine(" <TablixColumnHierarchy>"); sb.AppendLine("<TablixMembers>"); for (int i = 0; i < datos.Columns.Count; i++) sb.AppendLine("<TablixMember />"); sb.AppendLine("</TablixMembers>"); sb.AppendLine("</TablixColumnHierarchy>"); sb.AppendLine(" <TablixRowHierarchy>"); sb.AppendLine("<TablixMembers>"); sb.AppendLine("<TablixMember><KeepWithGroup>After</KeepWithGroup></TablixMember>"); for (int i = 0; i < datos.Rows.Count; i++) sb.AppendLine(string.Format("<TablixMember />")); sb.AppendLine("</TablixMembers>"); sb.AppendLine("</TablixRowHierarchy>"); sb.AppendLine(" <Top>0.05556in</Top>"); sb.AppendLine(" <Left>0.11458in</Left>"); sb.AppendLine(" <Height>1.25in</Height>"); sb.AppendLine(string.Format(" <Width>8in</Width>")); sb.AppendLine(" <Style>"); sb.AppendLine(" <Border>"); sb.AppendLine(" <Style>None</Style>"); sb.AppendLine(" </Border>"); sb.AppendLine(" </Style>"); sb.AppendLine(" </Tablix>"); return sb.ToString(); } 
  2. 然后,您將創建一種方法,該方法將讀取舊的rdlc文件並編寫新的rdlc文件以用於ReportViewer對象。

此方法如下所示:

/// <summary>
    /// Read the old rdlc file and write the new one to be used for ReportViewer
    /// </summary>
    /// <param name="datos">DataTable complete from Select statement</param>
    /// <param name="rutaActualRDLC">C\Reports\Template.rdlc</param>
    /// <param name="rutaNuevaRDLC">C\Reports\NewFile.rdlc</param>
    private void LecturaRDLCXML(DataTable datos, string rutaActualRDLC, string rutaNuevaRDLC)
    {
        //Read the report file into a XMLDocument
        XmlDocument documento = new XmlDocument();
        documento.Load(rutaActualRDLC);

        //Select the node 'ReportItems' that apear when you add a Tablix element empty
        XmlNode aNode = documento.DocumentElement.FirstChild.FirstChild;

        //Override that node with your DataTable, the same DataTable you passed to a DataGridView
        aNode.InnerXml = CrearTablaDeReporteXML(datos);
        //Save the new file written
        documento.Save(rutaNuevaRDLC);
    }

最后,您必須調用報告並傳遞新的報告路徑,如下所示:

private void btn_print_report(object sender, RoutedEventArgs e)
{
      //Remove the report dynamic that was create before
        string rutaNuevaRDLC = @"Reportes/rpt_dynamic_SQL_dinamico.rdlc";
        if (File.Exists(rutaNuevaRDLC))
            File.Delete(rutaNuevaRDLC);

      //Read the old and the new file
      //result is a DataTable type that contain the result of "Select * From Table"
        LecturaRDLCXML(result, @"Reportes/rpt_dynamic_SQL.rdlc", rutaNuevaRDLC);

      //Optional: if you have any other DataSources in your report
      //reportViewer.LocalReport.DataSources.Clear();
      //reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSourceName", IEunumerableCollectionForThisDataSource));

      reportViewer.LocalReport.ReportPath = rutaNuevaRDLC;
      reportViewer.Visible = true;
      reportViewer.LocalReport.Refresh();
      reportViewer.RefreshReport();
}

我希望這篇文章可以幫助別人helps

        cmdSave.PerformClick();
        string sqlCmd = "Update tbl_Ledger " +
                        " Set RSelected=0";
        DataAccess.ExecuteSQL(sqlCmd);

        string sqlCmd2 = "Update tbl_Ledger " +
                         " Set RSelected=1 " +
                         " where supplierid=" + this.txtSupplierID.Text + 
                         " AND  xRecDate BETWEEN '" + DateFrom.Text + "' AND    '" + DateTo.Text + "'";
        DataAccess.ExecuteSQL(sqlCmd2);



        Ledger.LedgerRep go = new Ledger.LedgerRep();
        go.supplierID = this.txtSupplierID.Text;
        go.RSelected = "1";
        go.Show();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM