【问题标题】:How to perform calculation in DataGridView when a checkbox is ticked C#勾选复选框时如何在DataGridView中执行计算C#
【发布时间】:2015-02-27 15:39:01
【问题描述】:

  • 我在 C# Datagridview 中有这个案例。

我想计算3件平均值,在上面显示的文本框上,只要检查复选框。

我在下面使用这个逻辑:

 private void button1_Click(object sender, EventArgs e)
    {


        DataGridView data = this.qualitySetupDataGridView;
        try
        {
            int count = 0;
            double Sum = 0;

            for (int k = 0; k < data.Rows.Count - 1; k++)
            {

                if (data.Rows[k].Cells[5].Value != null)
                {
                    if (Convert.ToBoolean(data.Rows[k].Cells[5].Value) == true)
                    {

                        double EndsPerInch = double.Parse(data.Rows[k].Cells[4].Value.ToString());
                        Sum = Sum + EndsPerInch;
                        count++;
                        double Average = Sum / count;
                        textBox1.Text = Convert.ToString(Math.Round(Average, 2));

                    }

                }

                else
                {

                    textBox1.Clear();

                }
            }
  • 代码运行正常。
  • 但第一次选择单个复选框时,我收到 Invalid Cast Exception 错误。
  • 当第二个复选框被选中时,我再次收到 Invalid Cast Exception Error。
  • 当第三个复选框被选中时,我没有收到 Invalid Cast Exception 错误。
  • 然后程序按预期运行。

  • 这里的问题是为什么一开始就弹出invalid cast exception错误?。

有没有更好的方法来实现这一点?

【问题讨论】:

  • 显然这将有助于 a) 查看 DGV 的相关代码和 b) 了解哪一行给出了无效的强制转换异常

标签: c# checkbox datagridview


【解决方案1】:

我认为您应该尝试使用更面向对象的逻辑,这样您就可以轻松计算平均值,而无需实际读取网格。

为此,您应该:

1.创建一个包含您的记录的类,如下所示:

public class MyRecord
{
     public double EndsPerInch { get; set; }
     public bool Checked { get; set; }
     //...and other properties I can't see from your screenshot
}

2.实例化 MyRecords 列表,即您将在网格中显示的记录列表:

List<MyRecord> MyRecords = new List<MyRecord>();

3.创建一个方法,用您的数据填充您的记录列表并将其绑定到您的数据网格视图中

private void LoadGrid()
{
    //Creating the list of records
    MyRecords.Add(new MyRecord { Checked = false, EndsPerInch = 92});
    MyRecords.Add(new MyRecord { Checked = false, EndsPerInch = 56 });
    MyRecords.Add(new MyRecord { Checked = false, EndsPerInch = 100 });

    //Binding the list of records to the datagridview
    //By doing so, a checkbox column will automatically be generated and bound
    //to the "Checked" property of your class
    dataGridView1.DataSource = MyRecords;
}

现在您已经拥有了可以正确绑定数据的一切。每次用户检查“已检查”列中的值时,对象记录的属性也将被更新。 从这里开始,通过从您的记录集合中选择检查值来计算平均值变得非常容易:

private double CalculateAverage(List<MyRecord> MyRecords)
{
    double Sum = 0;

    //Getting the list of checked records and calculating sum
    List<MyRecord> Checked = MyRecords.Where(x => x.Checked).ToList();
    foreach (MyRecord mr in Checked)
        Sum += mr.EndsPerInch;

    //Calculating and returning average
    return Sum / Checked.Count;
}

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2016-05-04
    • 1970-01-01
    • 2013-06-14
    • 2016-02-28
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    相关资源
    最近更新 更多