vendredi 27 février 2015

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

enter image description here



  • I have this case in C# Datagridview.


I want to calculate 3-Piece Average, on textbox shown above, whenever checkbox is checked.


I'm using this logic below:



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

}
}



  • The code is working as it suppose to be.

  • but first time, when a single checkbox is selected, I get Invalid Cast Exception Error.

  • when a second checkbox is selected I again get Invalid Cast Exception Error.

  • When third checkbox is selected I do not get Invalid Cast Exception Error.


  • and then the program works as it suppose to be.




  • The question here is this why it pops up invalid cast exception error in the beginning?.




is there a better way to achieve this?





Aucun commentaire:

Enregistrer un commentaire