// 清空所有的Series和Points chart1.Series.Clear(); chart1.Palette = ChartColorPalette.Pastel; chart1.Titles.Add("用户人数统计"); // 添加一个名为"Users"的Series Series series = chart1.Series.Add("Users"); series.ChartType = SeriesChartType.Pie; // 添加数据点 string constr = SqlHelper.sqlcon; NpgsqlConnection conn = new NpgsqlConnection(constr); NpgsqlDataAdapter AdapterSelect = new NpgsqlDataAdapter(); conn.Open(); NpgsqlCommand sqlCmd1 = new NpgsqlCommand(); string sql1 = "select count(*) from login where isAdmin = '1' "; //显示管理员人数 sqlCmd1 = new NpgsqlCommand(sql1, conn); object result1 = sqlCmd1.ExecuteScalar(); NpgsqlCommand sqlCmd2 = new NpgsqlCommand(); string sql2 = "select count(*) from login where isAdmin = '0' "; //显示一般用户人数 sqlCmd1 = new NpgsqlCommand(sql2, conn); object result2 = sqlCmd1.ExecuteScalar(); series.Points.AddXY("一般用户", result2); series.Points.AddXY("管理员", result1); // 设置标签和颜色 series.LabelFormat = "{0}%"; foreach (DataPoint point in series.Points) { point.Label = "#VALX: #VALY"; if (point.AxisLabel == "一般用户") point.Color = Color.Green; else if (point.AxisLabel == "管理员") point.Color = Color.Red; }百分数未显示
时间: 2023-06-25 16:05:31 浏览: 99
在这段代码中,设置了`series.LabelFormat = "{0}%"`来设置标签格式为百分数,但是在循环中设置了点的标签为`point.Label = "#VALX: #VALY"`,这会覆盖掉之前设置的百分数格式,导致标签中不能正确显示百分数。
解决方法是将循环中设置标签的代码注释掉或删除,这样就能正确显示百分数了。代码修改如下:
```
// 清空所有的Series和Points
chart1.Series.Clear();
chart1.Palette = ChartColorPalette.Pastel;
chart1.Titles.Add("用户人数统计");
// 添加一个名为"Users"的Series
Series series = chart1.Series.Add("Users");
series.ChartType = SeriesChartType.Pie;
// 添加数据点
string constr = SqlHelper.sqlcon;
NpgsqlConnection conn = new NpgsqlConnection(constr);
NpgsqlDataAdapter AdapterSelect = new NpgsqlDataAdapter();
conn.Open();
NpgsqlCommand sqlCmd1 = new NpgsqlCommand();
string sql1 = "select count(*) from login where isAdmin = '1' "; //显示管理员人数
sqlCmd1 = new NpgsqlCommand(sql1, conn);
object result1 = sqlCmd1.ExecuteScalar();
NpgsqlCommand sqlCmd2 = new NpgsqlCommand();
string sql2 = "select count(*) from login where isAdmin = '0' "; //显示一般用户人数
sqlCmd2 = new NpgsqlCommand(sql2, conn);
object result2 = sqlCmd2.ExecuteScalar();
series.Points.AddXY("一般用户", result2);
series.Points.AddXY("管理员", result1);
// 设置标签和颜色
series.LabelFormat = "{0}%";
foreach (DataPoint point in series.Points)
{
// 将下面这行代码注释掉或删除
// point.Label = "#VALX: #VALY";
if (point.AxisLabel == "一般用户")
point.Color = Color.Green;
else if (point.AxisLabel == "管理员")
point.Color = Color.Red;
}
```
阅读全文