uhey jeremy 同人:实例293 柱形图表分析投票结果

来源:百度文库 编辑:偶看新闻 时间:2024/06/11 11:44:15
柱形图表
随着编程技术的发展,图表技术已经越来越受到人们的欢迎。本节中,通过几个实例分别介绍用柱形图表显示数据库中数据的方法。
实例293  柱形图表分析投票结果
实例说明
在一些网站中,经常需要对相关的信息进行调查统计,然后根据访问者的投票结果制定相关计划,为了能够更直观地查看访问者的投票结果,本实例采用了柱形图表显示的方式实现了此目的,实例运行结果如图13.6所示。
  
图13.6  柱形图表分析投票结果
技术要点
本实例首先通过SQL语句从数据库中检索出相对应的数据,然后通过控制图片的大小来显示相关主题所对应的比例。由于数据库中的数据是以“|”符来分隔数据的,因此在检索数据库中的数据之前,应该对数据库中相应字段的数据进行处理,本实例主要通过Split方法实现,Split方法的语法格式如下。
public string[] Split (params char[] separator)
separator:分隔此实例中子字符串的Unicode字符数组,不包含分隔符的空数组或空引用。
实现过程
(1)新建一个网站,将其命名为Ex13_06,默认主页为Default.aspx,添加新Web窗体,将其命名为Result.aspx。
(2)Result.aspx页面后台代码中自定义了3个方法,分别用来显示图像、票数求和以及计算百分比,其中GetResult(string strContent, decimal decNumAll)方法用来显示图像,代码如下:
public string GetResult(string strContent, decimal decNumAll)
{
string[] arrContent = strContent.Split('|');
string strBody = "
\n";
foreach (string strContentIN in arrContent)
{
string strItemName = strContentIN.Split(',')[1].
ToString( );//得到选项名称
decimal decItemNum = Convert.ToDecimal
(strContentIN.Split(',')[0]);//得到选项的投票数
decimal decPercent = GetPercent(decItemNum, decNumAll) * 100;//得到百分比
string strPercent = decPercent.ToString( );//将百分比转为字符型
if (strPercent.Length > 5)//如果百分比结果长度超过5位
{
strPercent = strPercent.Substring(0, 5);//将百分比的余数截短为"00.00"
}
strBody += "\n";
}
strBody += "
9pt;text-align:center>" + strItemName + "
color=red;text-align:center>" + decItemNum.ToString( )
+ "票
gif height=10 width=" +  strPercent + "%>" + strPercent + "%
";
return strBody;
}
GetNumAll(string strNum)方法用来进行票数求和,以便进行百分比计算,代码如下:
public decimal GetNumAll(string strNum)
{
decimal decNumAll = 0;
string[] arrNum = strNum.Split('|');
foreach (string strNumIN in arrNum)
{
decNumAll += Convert.ToInt32(strNumIN.Split
(',')[0].ToString( ));//截取第零位
}
return decNumAll;
}
GetPercent(decimal decItem, decimal decNumAll)方法是用
来显示计算某一主题占总票数的百分比,代码如下:
public decimal GetPercent(decimal decItem, decimal decNumAll)
{
if (decNumAll == 0)//如果总票数是零
{
decNumAll++;//加一,避免除0出错
}
decimal decPercent = decItem / decNumAll;
return decPercent;
}
举一反三
根据本实例,读者可以:
实现图表显示网站全年各月份访问人数;
开发公司各部门销售业绩。