使用以下代码可以实现根据 DataGridView 选中行数据绘制柱状图的功能:

private void btnDrawChart_Click(object sender, EventArgs e)
{
    // 检查 DataGridView 是否有选中行
    if (dataGridView1.SelectedRows.Count == 0)
    {
        MessageBox.Show('请先选中一行数据');
        return;
    }

    // 读取选中行的数据
    int rowIndex = dataGridView1.SelectedRows[0].Index;
    int productionQty = Convert.ToInt32(dataGridView1.Rows[rowIndex].Cells['生产数量'].Value);
    int storageQty = Convert.ToInt32(dataGridView1.Rows[rowIndex].Cells['缴库数量'].Value);
    string product = dataGridView1.Rows[rowIndex].Cells['生产成品'].Value.ToString();

    // 清空图表数据
    chart1.Series.Clear();
    chart1.Titles.Clear();

    // 添加柱状图系列
    Series series = new Series(product);
    series.ChartType = SeriesChartType.Column;
    series.Points.AddXY('生产数量', productionQty);
    series.Points.AddXY('缴库数量', storageQty);

    // 添加图表标题
    Title title = new Title('生产数量和缴库数量柱状图');
    chart1.Titles.Add(title);

    // 添加系列到图表
    chart1.Series.Add(series);
}

在上述代码中,假设按钮 btnDrawChart_Click 为点击事件,当点击该按钮时,会执行上述代码。其中,dataGridView1 是 DataGridView 控件的名称,chart1 是 Chart 控件的名称。

以上代码中,首先检查 DataGridView 是否有选中行,如果没有选中行则弹出提示框。如果有选中行,则读取选中行的'生产数量'和'缴库数量'数据,以及'生产成品'名称。

然后,清空图表数据和标题,创建一个柱状图系列,并将选中行的'生产数量'和'缴库数量'作为柱状图的数据点添加到系列中。

最后,创建一个图表标题,并将系列添加到图表中。点击按钮后,图表将显示选中行的'生产数量'和'缴库数量'的柱状图。

C# DataGridView 选中行数据绘制柱状图

原文地址: https://www.cveoy.top/t/topic/qr5A 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录