c# datatable Chart
时间: 2023-11-03 14:06:53 浏览: 91
可以使用 C# 的 DataTable 类和 Chart 控件来生成图表。首先,你需要将数据填充到 DataTable 中,然后使用 Chart 控件来显示该 DataTable 中的数据。以下是一个示例代码:
```csharp
using System;
using System.Data;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
public partial class Form1 : Form
{
private DataTable dataTable;
private Chart chart;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// 创建一个 DataTable 并添加数据
dataTable = new DataTable();
dataTable.Columns.Add("Category", typeof(string));
dataTable.Columns.Add("Value", typeof(int));
dataTable.Rows.Add("Category 1", 10);
dataTable.Rows.Add("Category 2", 20);
dataTable.Rows.Add("Category 3", 30);
// 创建一个 Chart 控件并设置数据源
chart = new Chart();
chart.DataSource = dataTable;
// 创建一个 Series 并指定 X 和 Y 值
Series series = chart.Series.Add("Series1");
series.XValueMember = "Category";
series.YValueMembers = "Value";
// 设置图表类型为柱状图
series.ChartType = SeriesChartType.Column;
// 将 Chart 控件添加到窗体中
Controls.Add(chart);
}
}
```
请注意,上述示例使用 Windows Forms 应用程序来显示图表。如果你正在使用其他类型的应用程序(如 WPF 或 ASP.NET),你需要相应地调整代码。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)