C#2015 winform datagrid视图选中行到rdlc报告

时间:2016-11-14 13:33:19

标签: c# winforms datagridview rdlc

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

我已经使用表单和显示完成了CRUD操作,记录在datagridview,似乎工作正常。

现在,我想要的是将选定的rows gridview显示在报告中并打印出来。此外,我不希望它们显示为表格,而是每个记录的表格。因此,如果选择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();
}

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

让我知道我是否走错了路,或者我应该为此做些什么?您可以提供答案或至少提供一些我可能得到的信息。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

是否要传递查询结果,如&#34;选择*来自TableName&#34;到DataView的对象到ReportViewer?

你必须做这样的事情:

  1. 创建一个包含至少一个Tablix对象的新rdlc文件
  2. 确保新的rdlc文件的Build Action Property设置为&#39; Content&#39;并复制到输出目录以“始终复制”
  3. 创建接收查询的方法
  4. 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对象的新文件。

    3. 此方法如下所示:

      /// <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();
      }
      

      我希望这篇文章可以帮助别人☺

答案 2 :(得分:0)

 System.out.println("principalName----"+WebUtils.getCookie(httpServletRequest,  "principalName"));