Friday, September 23, 2005

Visual Studio 2005 的ReportViewer

Team里用Visual Studio 2005做开发一有三个月了,在这三个月里已经重装了Visual Studio 2005 三次了。先是June 的CTP(Community Technology Preview)版本,发现ReportViewer控件在Design模式下,不管是Win Form还是Web Form属性显示是空的,然后回到Beta 2, 属性显示正常了,但是在Web上Paging和Zoom时会出错,这时刚好要给客户Demo, 只好当夜换成Aug 的CTP版本。这次Paging和Zoom都没有问题,而且还多了导出到PDF和Excel的功能。最后还是有Bug, 当Refresh时ObjectDataSource不会保持ViewState!
这个问题出在我们是程序动态给ObjectDataSource赋值,代码如下:
///
/// Function to create report using ReportViewer in UserControl
///

/// Full path name of .rdlc file
/// The datasource name use in .rdlc file
/// The class name in which provide a method to retrieve data for report
/// The method name in a class to retrieve data for report, this method can return a IList as datasource for report
/// Parameter collection to pass to the method
/// Parameters to pass to report (.rdlc)
public void CreateReport(string reportRdlc, string datasourceName, string dsTypeName, string dsSelectMethod, ParameterCollection dsParamas, Microsoft.Reporting.WebForms.ReportParameter[] repParams)
{
//ObjectDataSource ObjectDataSource1 = new ObjectDataSource(dsTypeName, dsSelectMethod);
hid_dataSourceTypeName = dsTypeName;
hid_dataSourceSelectMethod = dsSelectMethod;
ObjectDataSource1.TypeName = dsTypeName;
ObjectDataSource1.SelectMethod = dsSelectMethod;
//ObjectDataSource1.ID = datasourceName;
ObjectDataSource1.SelectParameters.Clear();
foreach (Parameter p in dsParamas)
{
ObjectDataSource1.SelectParameters.Add(p);
}
ReportViewer1.Attributes.Add("hid_dataSourceTypeName", dsSelectMethod);
ReportViewer1.Attributes.Add("hid_dataSourceSelectMethod", dsSelectMethod);
this.ReportViewer1.LocalReport.DisplayName = reportRdlc.Replace(".rdlc","");
this.ReportViewer1.LocalReport.ReportPath = reportRdlc;

this.ReportViewer1.LocalReport.DataSources.Clear();
Microsoft.Reporting.WebForms.ReportDataSource reportDatasource1 = new Microsoft.Reporting.WebForms.ReportDataSource();
reportDatasource1.Name = datasourceName;
//reportDatasource1.DataSourceId = datasourceName;
reportDatasource1.DataSourceId = ObjectDataSource1.ID;
this.ReportViewer1.LocalReport.DataSources.Add(reportDatasource1);
this.ReportViewer1.LocalReport.SetParameters(repParams);
this.ReportViewer1.LocalReport.Refresh();
}

最后跟踪发现Refresh回到服务器之后,用ReportViewer的Refresh之后,ObjectDataSource的TypeName和SelectMethod的值就丢了。只好给他加个补丁:
protected void ReportViewer1_PreRender(object sender, EventArgs e)
{
ObjectDataSource1.TypeName = hid_dataSourceTypeName;
ObjectDataSource1.SelectMethod = hid_dataSourceSelectMethod;
}
public string hid_dataSourceTypeName
{
get { return Convert.ToString(ViewState["hid_dataSourceTypeName"]); }
set { ViewState["hid_dataSourceTypeName"] = value; }
}
public string hid_dataSourceSelectMethod
{
get { return Convert.ToString(ViewState["hid_dataSourceSelectMethod"]); }
set { ViewState["hid_dataSourceSelectMethod"] = value; }
}
不知道大家有没有其它办法。

No comments: