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

C# WinForm中如何在Crystal Report视图展示数据库指定行数据

实现Crystal Report展示指定行数据的调整方案

方案1:SQL层面过滤(推荐,性能更高)

这种方式直接在数据库查询阶段筛选需要的行,避免加载全量数据浪费资源,同时用参数化查询避免SQL注入风险。

调整步骤:

  • 确定你的筛选条件,比如按MemberId、会员手机号、注册时间等字段筛选
  • 修改原SQL查询语句,增加WHERE条件,通过参数传值
  • 优化数据库连接释放逻辑,使用using自动管理资源

调整后代码:

private void AllMemberReportForm_Load(object sender, EventArgs e)
{
    ReportDocument crypt = new ReportDocument();

    string AppPath = Application.StartupPath;
    string ReportPath = @"AllMemberReport.rpt";
    string ReportFullPath = Path.Combine(AppPath, ReportPath);

    // 这里替换为你实际要筛选的条件值,比如从窗体文本框/全局变量传过来的指定会员ID
    int targetMemberId = 1001; 

    // 使用using自动释放连接资源,无需手动Close
    using (SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\GymDatabase.mdf;Integrated Security=True;Connect Timeout=30"))
    {
        // 新增WHERE条件,用参数占位符避免SQL注入
        string querySql = "select * from Member where MemberId = @TargetId";
        SqlDataAdapter dadptr = new SqlDataAdapter(querySql, connection);
        // 给参数赋值
        dadptr.SelectCommand.Parameters.AddWithValue("@TargetId", targetMemberId);

        DataSet dset = new DataSet();
        dadptr.Fill(dset);

        crypt.Load(ReportFullPath);
        crypt.SetDataSource(dset);
        crystalReportViewer1.ReportSource = crypt;
    }
}

如果需要多条件筛选,直接在WHERE后加多个条件即可,比如where MemberId = @TargetId and RegisterTime >= @StartTime,对应补充参数赋值即可

方案2:DataSet层面过滤(适合已加载全量数据的场景)

如果你已经拿到了全量Member的DataSet,不想再查数据库,可以直接在内存中过滤数据:

// 原加载全量数据的代码不变,填充dset后增加过滤逻辑
DataRow[] filteredRows = dset.Tables[0].Select("MemberId = 1001");
// 把过滤后的行导入新表绑定到报表
DataTable filterTable = dset.Tables[0].Clone();
foreach (DataRow row in filteredRows)
{
    filterTable.ImportRow(row);
}
crypt.SetDataSource(filterTable);

注意事项

  • 筛选字段要和你Member表的实际字段名完全一致,拼写错误会导致查询失败
  • Crystal Report模板的字段绑定要和返回的数据集字段匹配,不要出现报表有绑定字段但查询结果没有的情况
  • 如果筛选值是字符串类型,参数化查询会自动处理格式,不需要手动加单引号

内容的提问来源于stack exchange,提问作者Atif Murtaza 2311

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:06:03