繁体   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