VS2017 WinForms工具ReportViewer V14表达式求值程序集加载异常问题
我之前在VS2017里做WinForms工具+ReportViewer 14时也踩过这个坑,刚好就是用IIf表达式设置字体/颜色/背景色的时候炸了,太懂这种崩溃的感觉了!本质原因是ReportViewer执行表达式时,依赖的宿主程序集找不到Microsoft.ReportViewer.Common 14.0.0.0版本,给你几个靠谱的解决办法:
检查项目引用的“复制本地”属性
右键你的项目→引用,找到Microsoft.ReportViewer.Common和Microsoft.ReportViewer.WinForms,右键打开属性面板:- 把「复制本地」改成
True,这样编译时会把对应dll复制到输出目录,避免运行时找不到。 - 确认「版本」确实是14.0.0.0,别不小心混了其他版本的引用(比如12.0或15.0)。
- 把「复制本地」改成
手动补齐输出目录的程序集
编译后去项目的bin/Debug(或Release)文件夹里看看,有没有Microsoft.ReportViewer.Common.dll、Microsoft.ReportViewer.WinForms.dll这两个核心文件。如果没有,直接从VS安装目录复制:
路径大概是C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\ReportViewer(把Community换成你VS的版本,比如Professional/Enterprise),把里面对应的dll复制到输出目录即可。确认GAC里有正确版本的程序集
打开管理员命令提示符,运行:gacutil /l Microsoft.ReportViewer.Common如果列表里没有14.0.0.0版本的,说明VS安装时ReportViewer组件没装全。打开VS Installer,找到你的VS2017实例,点「修改」,在「单个组件」里找到「Reporting Services - Report Viewer」相关组件,勾选后重新安装修复。
修正App.config的绑定重定向
打开项目的App.config,检查有没有ReportViewer的绑定重定向配置。如果有旧版本的绑定,改成14.0.0.0的配置:<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.ReportViewer.Common" publicKeyToken="89845dcd8080cc91" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-14.0.0.0" newVersion="14.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.ReportViewer.WinForms" publicKeyToken="89845dcd8080cc91" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-14.0.0.0" newVersion="14.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>顺带检查表达式语法(小细节)
虽然主要问题是程序集,但有时候表达式的小错误也会触发奇怪的异常。比如确认你的表达式是=IIf(Fields!Value.Value="some text","White","Black"),注意字段后面的.Value(如果字段是可空类型的话,必须加这个才能正确取值)。
如果以上都试过还是不行,试试右键项目→清理,然后删除bin和obj文件夹,再重新编译一次,有时候缓存问题也会搞事情。
内容的提问来源于stack exchange,提问作者Ahmad Hamdy

