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

如何在ASP.Net的CrystalReportViewer_Init函数中通过QueryString获取参数?

没问题,你完全可以在CrystalReportViewer1_Init事件里接收URL参数,不过你的代码里有几个关键问题需要修正,我帮你梳理下:

1. QueryString键名的空格错误

你的代码里写了Request.QueryString[" filename "],键名前后多了空格,但实际URL里的参数是filename(无空格),这会导致找不到参数值,直接抛出空引用异常。必须把空格去掉,改成Request.QueryString["filename"]。

2. 缺少空值判断,存在崩溃风险

直接调用.ToString()很危险——如果URL里没传filename参数、参数值为空,或者参数名拼写错误,都会触发空引用错误。建议先做参数有效性校验。

3. 关于Init事件接收参数的可行性

Init事件属于页面生命周期较早的阶段,但Request.QueryString在这个阶段是可以正常访问的,所以完全没问题。你的场景是从其他页面跳转过来,不存在回发状态恢复的额外问题,这个事件是合适的选择。

修正后的完整代码示例

protected void CrystalReportViewer1_Init(object sender, EventArgs e)
{
    ReportDocument _rdStudents = new ReportDocument();
    string reportFileName = Request.QueryString["filename"];
    
    // 先校验参数是否有效
    if (!string.IsNullOrEmpty(reportFileName))
    {
        string reportPath = Server.MapPath("~/CrystalReportFiles/Inventory/" + reportFileName);
        _rdStudents.Load(reportPath);
        CrystalReportViewer1.ReportSource = _rdStudents;
    }
    else
    {
        // 可选:参数缺失时加载默认报表,或者给出友好提示
        string defaultReportPath = Server.MapPath("~/CrystalReportFiles/Inventory/WeightBarcorde.rpt");
        _rdStudents.Load(defaultReportPath);
        CrystalReportViewer1.ReportSource = _rdStudents;
    }
}

另外提个小细节:你的跳转链接里写的是CrytalReportTest.aspx(少了一个s,正确应该是CrystalReportTest.aspx),如果实际页面文件名是正确拼写的话,这个小错误也会导致跳转失败,建议检查一下页面文件名和链接的一致性。

内容的提问来源于stack exchange,提问作者mohamed faisal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:24:03