ActiveReports是目前生成和显示报表效率最高的报表控件,但是由于某些报表长度非常大,如果要生成或运行非常大的报表,ActiveReports还是需要一段时间,这段时间可能是几秒,最长也可能达到几十秒,这时进度条的需求就出现了。最终用户需要一个进度条来显示 报表生成的进度,不然最终用户可能将正常报表生成时间理解为应用系统的不稳定。
虽然ActiveReports的报表浏览器并没有显示进度条的功能,但是ActiveReports惊人的灵活性允许开发者将一个用户显示报表生成进度的进度条集成到报表浏览器中,类似一下效果:
我们需要Windows forms ProgressBar 这个控件,此外还需要一个标签控件用于显示进度的百分比和提示报表生成完成。
首先要确定报表记录数来确定进度条的最大值,ActiveReports支持多种类型的数据源,所以还要确定报表使用的数据源类型,下面的代码示例就是创建一个GetNoOfRecords函数来计算记录数,这种方式适用于常见数据源。
public int GetNoOfRecords(object ds)
{
int noOfRecs = 0;
if (ds.GetType().ToString() == "GrapeCity.ActiveReports.Data.SqlDBDataSource")
{
GrapeCity.ActiveReports.Data.SqlDBDataSource ods = (GrapeCity.ActiveReports.Data.SqlDBDataSource)ds;
SqlConnection con = new SqlConnection(ods.ConnectionString);
SqlCommand com = new SqlCommand("Select count(*) as totalRecs from (" + ods.SQL + ")", con);
con.Open();
SqlDataReader sdr = com.ExecuteReader();
sdr.Read();
if (sdr.HasRows)
{
noOfRecs = Convert.ToInt32(sdr[0]);
}
con.Close();
}
else if (ds.GetType().ToString() == "GrapeCity.ActiveReports.Data.OleDBDataSource")
{
GrapeCity.ActiveReports.Data.OleDBDataSource ods = (GrapeCity.ActiveReports.Data.OleDBDataSource)ds;
OleDbConnection con = new OleDbConnection(ods.ConnectionString);
OleDbCommand com = new OleDbCommand("Select count(*) as totalRecs from (" + ods.SQL + ")", con);
con.Open();
OleDbDataReader odr = com.ExecuteReader();
odr.Read();
if (odr.HasRows)
{
noOfRecs = Convert.ToInt32(odr[0]);
}
con.Close();
}
else if (ds.GetType().ToString() == "GrapeCity.ActiveReports.Data.XMLDataSource")
{
GrapeCity.ActiveReports.Data.XMLDataSource xds = (GrapeCity.ActiveReports.Data.XMLDataSource)ds;
noOfRecs = xds.NodeList.Count;
}
else if (ds.GetType().ToString() == "System.Data.DataTable")
{
System.Data.DataTable dtds = (System.Data.DataTable)ds;
noOfRecs = dtds.Rows.Count;
}
else
{
GrapeCity.ActiveReports.Data.ListDataSource lds = (GrapeCity.ActiveReports.Data.ListDataSource)ds;
noOfRecs = lds.List.Count;
}
return noOfRecs;
}
在得到记录数后,需要将其值设置为最大进度数,并在一个单独的线程中运行的ActiveReports。在单独进程运行报表能够实现报表的后台运行而 且能获取报表进度。接下来定义一个在FetchData事件中递增的变量recordCount,这个变量将用来控制进度条的运动,示例代码如下所示:
private void CheckProgress(object sender, EventArgs e)
{
if (progressBar1.Maximum > recordCount)
{
progressBar1.Value = recordCount;
label1.Text = ((int)((progressBar1.Value * 100) / progressBar1.Maximum)).ToString() + "%";
}
else
{
timer1.Enabled = true;
label1.Text = "Done!";
progressBar1.Value = progressBar1.Maximum;
StopTimer();
}
}
以上代码中的label1是用来显示进度百分比的。代码中也包含了停止和重启报表生成的按钮。