简体   繁体   English

提取datagridview值C#

[英]Extracting datagridview values C#

How do I calculate Cells with written values in the datagridview?如何在 datagridview 中计算具有写入值的单元格?

For example x= Cell1+Cell2 (10+10);例如 x= Cell1+Cell2 (10+10); Result: y1 = 20;结果:y1 = 20;

在此处输入图像描述

An easy way is to have a DataSource for your DataGridView, in the example below a DataTable is used, third column uses an expression to add the first two columns together.一种简单的方法是为您的 DataGridView 设置一个 DataSource,在下面的示例中使用了一个 DataTable,第三列使用表达式将前两列相加。

Even though a DataGridView works well without a DataSource especially in your case it works better as it ensures a proper type and auto calculations.即使 DataGridView 在没有 DataSource 的情况下也能很好地工作,尤其是在您的情况下,它会更好地工作,因为它可以确保正确的类型和自动计算。

And the BindingSource allows access to your data without touching the DataGridView. BindingSource允许在不接触 DataGridView 的情况下访问您的数据。

public partial class Form1 : Form
{
    private readonly BindingSource _bindingSource = new BindingSource();
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        _bindingSource.DataSource = DataTable();
        dataGridView1.DataSource = _bindingSource;
        dataGridView1.DataError += DataGridView1OnDataError;
    }

    private void DataGridView1OnDataError(object sender, DataGridViewDataErrorEventArgs e)
    {
        e.Cancel = true;
        MessageBox.Show("Wrong type");
    }

    private DataTable DataTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Col1", typeof(int));
        dt.Columns.Add("Col2", typeof(int));
        dt.Columns.Add("Total", typeof(int)).Expression = "Col1 + Col2";

        dt.Rows.Add(10, 10);
        return dt;
    }

    private void CurrentButton_Click(object sender, EventArgs e)
    {
        if (_bindingSource.Current == null)
        {
            return;
        }

        var row = ((DataRowView)_bindingSource.Current).Row;
        MessageBox.Show($"Total is {row.Field<int>("Total")}");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM