You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS2017中CrystalReport绑定DataSet打印标签仅显示字段无数据如何解决?

问题引发原因
  • 最核心的问题:设置好数据源的CrystalReport对象未与打印预览窗口的报表查看器控件绑定。你代码中创建了stickerprint报表实例cr并调用SetDataSource传入了数据集,但没有把cr赋值给prtsticker窗口内的报表查看器,预览窗口只加载了报表的静态字段结构,没有拿到运行时的动态数据。
  • 运行时创建的DataTable未显式设置表名:如果CrystalReport设计阶段绑定的表名和运行时传入的表名不一致,报表也无法匹配到对应数据,默认创建的DataTable表名为Table1,很容易和设计时的表名不匹配。
  • 可选问题:循环遍历DataGridView行时未跳过空白新增行,若你开启了DataGridView的允许用户添加行功能,末尾的空白行可能会插入空数据,但不是本次无数据问题的核心原因。
  • 补充问题:ds.WriteXmlSchema("sticker.mdf")是无效代码,mdf是SQL Server数据库文件后缀,WriteXmlSchema是导出XML架构文件,后缀应为.xsd,且这行代码对本次打印逻辑没有作用,可以直接删除。
修复方案

首先确认你设计stickerprint报表时绑定的DataTable表名,假设设计时的表名为StickerData,按如下逻辑修改代码即可:

private void print_Click(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    DataTable dtd = new DataTable();
    // 1. 给DataTable设置和报表设计时一致的表名
    dtd.TableName = "StickerData";

    dtd.Columns.Add("Your P.O #", typeof(string));
    dtd.Columns.Add("Your Job #", typeof(string));
    dtd.Columns.Add("Title", typeof(string));
    dtd.Columns.Add("Quantity in the Box", typeof(string));
    dtd.Columns.Add("Box", typeof(string));
    dtd.Columns.Add("of", typeof(string));

    foreach (DataGridViewRow dtgvRow in dtgv.Rows)
    {
        // 2. 跳过DataGridView的空白新增行
        if (!dtgvRow.IsNewRow)
        {
            dtd.Rows.Add(dtgvRow.Cells[1].Value, dtgvRow.Cells[2].Value, dtgvRow.Cells[3].Value, dtgvRow.Cells[4].Value, dtgvRow.Cells[5].Value, dtgvRow.Cells[6].Value);
        }
    }

    ds.Tables.Add(dtd);

    prtsticker fm = new prtsticker();
    stickerprint cr = new stickerprint();

    cr.SetDataSource(ds);
    // 3. 把报表实例绑定到预览窗口的报表查看器上,默认控件名为crystalReportViewer1,你可以根据自己的实际控件名修改
    fm.crystalReportViewer1.ReportSource = cr;
    fm.crystalReportViewer1.RefreshReport();
    fm.Show();
}

如果你的prtsticker窗口内的报表查看器控件是私有成员,无法在外部直接赋值,可以在prtsticker窗口类里新增一个公共方法接收报表实例,再绑定到内部的查看器控件即可。

内容的提问来源于stack exchange,提问作者nabila semmache

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:54:07