【问题标题】:C# 2015 winform datagrid view selected rows to rdlc reportC# 2015 winform datagrid 查看选定行到 rdlc 报告
【发布时间】:2017-03-28 03:55:57
【问题描述】:

我是 Windows 应用程序和 C# 的新手。我将C# 2015 用于windows applicationMS-Access 2007 数据库。

我已经使用表单完成了 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();
}

我已经抛出了许多教程,但每个教程都使用直接连接到数据库的报表向导和数据集,在我的例子中,我使用的是列表。

如果我走错了路,或者我应该怎么做,请告诉我?你可以提供答案或至少一个链接,我可能会得到我想要的。

【问题讨论】:

  • 整体进度好像还可以,有什么问题吗?你收到异常了吗?
  • 在报表查看器中,它会打印“未指定某些参数或凭据”。但是,我不确定如何将列表元素映射到 rdlc 字段?
  • 所以这是因为您没有传递一些参数和凭据。要映射列表元素,它们与报告字段具有相同的名称就足够了。阅读一些关于常见问题的注释here。特别提示编号 2,3,4
  • 可能是的,我不知道该怎么做?有链接吗?另外,我没有为访问文件设置任何密码。我只是很困惑如何将列表的客户对象内的“id”分配给报告字段?

标签: c# winforms datagridview rdlc


【解决方案1】:

不需要所有这些代码 您只需在目标表或选择语句中添加一列 并为其分配一个值,例如RSelected =1 只需更新值以将 Re selected 保存为 1,然后您必须将其分配给 0 或您需要的任何值, 然后您可以在 SQL 语句中的代码中选择此值 就是这样)))))))

【讨论】:

    【解决方案2】:

    您是否要将“Select * From TableName”之类的查询结果传递到 DataTable 对象中并传递给 ReportViewer?

    你必须这样做:

    1. 创建一个包含至少一个 Tablix 对象的新 rdlc 文件
    2. 确保新的 rdlc 文件将构建操作属性设置为“内容”并将复制到输出目录设置为“始终复制”
    3. 创建接收查询的方法

    See the method created here

    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 文件并写入用于 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();
    }
    

    我希望这篇文章对其他人有所帮助☺

    【讨论】:

    • 感谢您发布答案。我会检查它,如果执行此代码有任何问题,我会通知您。
    【解决方案3】:
            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();
    

    【讨论】:

      猜你喜欢
      • 2017-08-08
      • 1970-01-01
      • 2020-11-02
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多