利用C#将设备用户数量和管理员数量画成饼图
时间: 2023-06-26 15:07:58 浏览: 52
要利用C#画饼图,可以使用.NET的Windows Forms应用程序来实现。下面是一个简单的示例代码,演示如何使用Chart控件来绘制饼图。
首先,需要在Visual Studio中创建一个Windows Forms应用程序。然后,在窗体上拖放一个Chart控件,并将其大小调整为适合的大小。
接下来,需要编写一些代码来添加数据和绘制饼图。以下是示例代码:
```csharp
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace PieChartExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// 添加数据
DataTable table = new DataTable();
table.Columns.Add("Type", typeof(string));
table.Columns.Add("Count", typeof(int));
table.Rows.Add("设备用户", 50);
table.Rows.Add("管理员", 10);
// 设置饼图属性
chart1.Series.Clear();
chart1.Series.Add("Data");
chart1.Series["Data"].ChartType = SeriesChartType.Pie;
chart1.Series["Data"].IsValueShownAsLabel = true;
chart1.Series["Data"].LabelFormat = "#.##%";
chart1.Series["Data"].Font = new Font("Arial", 10);
// 添加数据到饼图
foreach (DataRow row in table.Rows)
{
string type = row["Type"].ToString();
int count = Convert.ToInt32(row["Count"]);
chart1.Series["Data"].Points.AddXY(type, count);
}
// 设置颜色
chart1.Series["Data"].Points[0].Color = Color.Blue;
chart1.Series["Data"].Points[1].Color = Color.Red;
}
}
}
```
在上面的示例代码中,首先创建了一个包含设备用户和管理员数量的数据表。然后,设置了饼图的属性,包括图表类型、是否显示标签、标签格式、字体等。最后,将数据添加到饼图中,并设置了不同类型的数据点的颜色。
运行该应用程序,即可看到绘制的饼图。