从DataGridView在运行时动态创建RDLC报告

Gan*_*zy' 5 c# reportviewer datagridview rdlc winforms

我有一个AdvancedSearchForm带有DataGridView控件的表单dgrData和一个ReportC#Winform中的按钮.单击该按钮Report,我希望带有ReportView控件的表单显示与DataGridView中具有相同列标题的列相同的列.

使用DataGridView和Button进行表单

在此输入图像描述

单击按钮"报告"时预期的输出:

在此输入图像描述

我的DatagridView(dgrData)控件与

  1. SQL
“Select Id, c_Name from Country”
Run Code Online (Sandbox Code Playgroud)
  1. 的ConnectionString
server=localhost;User Id=root;password=root;Persist Security Info=True;database=country_state
Run Code Online (Sandbox Code Playgroud)

要在运行时将数据加载到网格,我准备以下DataAdapter:

DataAdapter dataAdapter = DataAdapter.Current;
// I am passing the SQL statement and the table name to my database which knows the ConnectionString within the LoadData function

DataTable dt0 = dataAdapter.LoadData("select Id, c_Name from `country`", "country");
if (dt0 != null) {
   dgrData.DataSource = dt0;
}
Run Code Online (Sandbox Code Playgroud)

是否可以调用包含默认reportviewer控件的子窗体,该窗口显示带有包含与datagridview(dgrData)对应的列的表的报告以及在运行时动态生成的数据?

输出预期详细:

  1. 单击按钮,目标表单上的reportviewer应该
    DataGridView中的值关联dataSource .因此,在用户在运行时单击"报告"按钮之前,ReportViewer控件对报告中的数据一无所知.
  2. 我希望解决方案不需要创建单独的RDLC文件,因为它会导致外部依赖,停止当前流并在报表文件设计器中创建一个报表文件,这可能会对用户产生过大的影响.
  3. 我对RDLC设计器和关联数据源一无所知(我愿意学习(^ _ ^),但我不能强迫我的团队学习此要求)并将数据绑定到报告.如果您的帮助包含理论,我将非常感谢编写代码示例.
  4. 我知道ReportViewer已经存在了很长时间了.希望将来更容易找到数据网格和ReportViewer之间1-1数据映射的示例解决方案.

注意:如果我在评论中需要任何其他数据,请告知我们.为了显示当前的解决方案,我必须创建和RDLC文件,我必须在设计时放置连接字符串和SQL,我希望在我正在寻找的解决方案中避免.我希望找到一个解决方案,其中RDLC文件是通过一些模块化代码生成的,这些代码也可以用在其他解决方案上,而不是必须为我拥有DataGrids的每个表单设计它.

Rez*_*aei 6

作为RDLC在运行时动态创建报表的选项,您可以使用运行时文本模板.

在下面的示例中,我创建了一个简单的网格报告,可用于在运行时动态创建报告.您可以动态添加列以进行报告,并为列设置标题,宽度,标题返回颜色.

在示例中,我使用了一个填充模板DataGridView.但您可以使用此技术依赖于任何类型的控制,甚至可以在Web表单中使用它.

示例用法 - 创建和显示动态报告

要创建和显示动态报告,只需添加一些列ReportForm,然后设置数据并显示表单即可.

var f = new ReportForm();
f.ReportColumns = this.dataGridView1.Columns.Cast<DataGridViewColumn>()
                      .Select(x => new ReportColumn(x.DataPropertyName)
                      { Title = x.HeaderText, Width = x.Width }).ToList();
f.ReportData = this.dataGridView1.DataSource;
f.ShowDialog();
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

解决方案的途径

这足以补充ReportColumnDynamicReport.ttReportForm你的应用程序,甚至在可重用库一次,然后简单地使用像上面的例子.按照以下步骤创建动态报告模板.

报告列模型

创建一个包含标题,表达式,颜色等属性的报表列模型.我们将使用它来添加要报告的列.

using System;
using System.Drawing;
public class ReportColumn
{
    public ReportColumn(string name)
    {
        Name = name;
        Title = name;
        Type = typeof(System.String);
        Width = GetPixelFromInch(1);
        Expression = string.Format("=Fields!{0}.Value", name);
        HeaderBackColor = Color.LightGray;
    }
    public string Name { get; set; }
    public string Title { get; set; }
    public Type Type { get; set; }
    public int Width { get; set; }
    public float WidthInInch
    {
        get { return GetInchFromPixel(Width); }
    }
    public string Expression { get; set; }
    public Color HeaderBackColor { get; set; }
    public string HeaderBackColorInHtml
    {
        get { return ColorTranslator.ToHtml(HeaderBackColor); }
    }
    private int GetPixelFromInch(float inch)
    {
        using (var g = Graphics.FromHwnd(IntPtr.Zero))
            return (int)(g.DpiY * inch);
    }
    private float GetInchFromPixel(int pixel)
    {
        using (var g = Graphics.FromHwnd(IntPtr.Zero))
            return (float)pixel / g.DpiY;
    }
}
Run Code Online (Sandbox Code Playgroud)

报告模板

将一个运行时模板(也称为预处理模板)添加到项目中并为其命名DynamicReport.tt并将此内容复制到该文件:

<#@ template language="C#" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ parameter name="Model" type="System.Collections.Generic.List<ReportColumn>"#>
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition">
  <DataSources>
    <DataSource Name="DataSource1">
      <ConnectionProperties>
        <DataProvider>System.Data.DataSet</DataProvider>
        <ConnectString>/* Local Connection */</ConnectString>
      </ConnectionProperties>
      <rd:DataSourceID>e9784bb0-a630-49cc-b7f9-8495aca23a6c</rd:DataSourceID>
    </DataSource>
  </DataSources>
  <DataSets>
    <DataSet Name="DataSet1">
      <Fields>
<#    foreach(ReportColumn column in Model){#>
        <Field Name="<#=column.Name#>">
          <DataField><#=column.Name#></DataField>
          <rd:TypeName><#=column.Type.Name#></rd:TypeName>
        </Field>
<#    }#>
      </Fields>
      <Query>
        <DataSourceName>DataSource1</DataSourceName>
        <CommandText>/* Local Query */</CommandText>
      </Query>
      <rd:DataSetInfo>
        <rd:DataSetName />
        <rd:TableName />
        <rd:ObjectDataSourceType />
      </rd:DataSetInfo>
    </DataSet>
  </DataSets>
  <Body>
    <ReportItems>
      <Tablix Name="Tablix1">
        <TablixBody>
          <TablixColumns>
<#    foreach(ReportColumn column in Model){#>
            <TablixColumn>
              <Width><#=column.WidthInInch#>in</Width>
            </TablixColumn>
<#    }#>
          </TablixColumns>
          <TablixRows>
            <TablixRow>
              <Height>0.25in</Height>
              <TablixCells>
<#    foreach(ReportColumn column in Model){#>
                <TablixCell>
                  <CellContents>
                    <Textbox Name="<#=column.Name#>TextBox">
                      <CanGrow>true</CanGrow>
                      <KeepTogether>true</KeepTogether>
                      <Paragraphs>
                        <Paragraph>
                          <TextRuns>
                            <TextRun>
                              <Value><#=column.Title#></Value>
                              <Style />
                            </TextRun>
                          </TextRuns>
                          <Style />
                        </Paragraph>
                      </Paragraphs>
                      <rd:DefaultName><#=column.Name#>TextBox</rd:DefaultName>
                      <Style>
                        <Border>
                          <Color>LightGrey</Color>
                          <Style>Solid</Style>
                        </Border>
                        <BackgroundColor><#=column.HeaderBackColorInHtml#></BackgroundColor>
                        <PaddingLeft>2pt</PaddingLeft>
                        <PaddingRight>2pt</PaddingRight>
                        <PaddingTop>2pt</PaddingTop>
                        <PaddingBottom>2pt</PaddingBottom>
                      </Style>
                    </Textbox>
                  </CellContents>
                </TablixCell>
<#    }#>
              </TablixCells>
            </TablixRow>
            <TablixRow>
              <Height>0.25in</Height>
              <TablixCells>
<#    foreach(ReportColumn column in Model){#>
                <TablixCell>
                  <CellContents>
                    <Textbox Name="<#=column.Name#>">
                      <CanGrow>true</CanGrow>
                      <KeepTogether>true</KeepTogether>
                      <Paragraphs>
                        <Paragraph>
                          <TextRuns>
                            <TextRun>
                              <Value><#=column.Expression#></Value>
                              <Style />
                            </TextRun>
                          </TextRuns>
                          <Style />
                        </Paragraph>
                      </Paragraphs>
                      <rd:DefaultName><#=column.Name#></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>
                  </CellContents>
                </TablixCell>
<#    }#>
              </TablixCells>
            </TablixRow>
          </TablixRows>
        </TablixBody>
        <TablixColumnHierarchy>
          <TablixMembers>
<#    foreach(ReportColumn column in Model){#>
            <TablixMember />
<#    }#>
          </TablixMembers>
        </TablixColumnHierarchy>
        <TablixRowHierarchy>
          <TablixMembers>
            <TablixMember>
              <KeepWithGroup>After</KeepWithGroup>
            </TablixMember>
            <TablixMember>
              <Group Name="Details" />
            </TablixMember>
          </TablixMembers>
        </TablixRowHierarchy>
        <DataSetName>DataSet1</DataSetName>
        <Top>0.15625in</Top>
        <Left>0.125in</Left>
        <Height>0.5in</Height>
        <Width>2in</Width>
        <Style>
          <Border>
            <Style>None</Style>
          </Border>
        </Style>
      </Tablix>
    </ReportItems>
    <Height>0.82292in</Height>
    <Style />
  </Body>
  <Width>6.5in</Width>
  <Page>
    <LeftMargin>1in</LeftMargin>
    <RightMargin>1in</RightMargin>
    <TopMargin>1in</TopMargin>
    <BottomMargin>1in</BottomMargin>
    <Style />
  </Page>
  <rd:ReportID>60987c40-62b1-463b-b670-f3fa81914e33</rd:ReportID>
  <rd:ReportUnitType>Inch</rd:ReportUnitType>
</Report>
Run Code Online (Sandbox Code Playgroud)

报表

添加一个Form项目并向ReportViewer表单添加一个控件,并将此代码放在类中:

public partial class ReportForm : Form
{
    public ReportForm()
    {
        InitializeComponent();
        ReportColumns  = new List<ReportColumn>();
        this.Load+=new EventHandler(ReportForm_Load);
    }

    public List<ReportColumn> ReportColumns { get; set; }
    public Object ReportData { get; set; }

    private void ReportForm_Load(object sender, EventArgs e)
    {
        var report = new DynamicReport();
        report.Session = new Dictionary<string, object>();
        report.Session["Model"] = this.ReportColumns;
        report.Initialize();
        var rds = new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", this.ReportData);
        this.reportViewer1.LocalReport.DataSources.Clear();
        this.reportViewer1.LocalReport.DataSources.Add(rds);
        var reportContent = System.Text.Encoding.UTF8.GetBytes(report.TransformText());
        using (var stream = new System.IO.MemoryStream(reportContent))
        {
            this.reportViewer1.LocalReport.LoadReportDefinition(stream);
        }
        this.reportViewer1.RefreshReport();
    }
}
Run Code Online (Sandbox Code Playgroud)

注意

您可以简单地扩展ReportColumn模型DynamicReport.tt.我使用现有报告创建了模板,我只使用了一些t4代码标签使其动态化.

您可以克隆或下载一个工作示例: