簡體   English   中英

當勾選復選框時,如何在DataGridView中執行計算C#

[英]How to perform calculation in DataGridView when a checkbox is ticked C#

在此輸入圖像描述

  • 我在C#Datagridview中有這種情況。

我想在選中復選框時計算上面顯示的文本框上的3-Piece Average。

我在下面使用這個邏輯:

 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();

                }
            }
  • 代碼正如它所設想的那樣工作。
  • 但是第一次,當選中一個復選框時,我會收到無效的強制轉換異常錯誤。
  • 當選擇第二個復選框時,我再次獲得無效的轉換異常錯誤。
  • 選中第三個復選框時,我不會收到無效的轉換異常錯誤。
  • 然后程序就像它想象的那樣工作。

  • 這里的問題是為什么它在開始時彈出無效的強制轉換異常錯誤?

有沒有更好的方法來實現這一目標?

我認為您應該嘗試使用更面向對象的邏輯,這樣您就可以輕松地計算平均值,而無需實際讀取網格。

為此你應該:

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.創建一個方法,用您的數據填充您的記錄列表並將其綁定在您的datagridview中

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM