Hi guys,

I've got a windows form with a datagridview linked to an access database. The third column in the datagridview is a list of numeric values. On load up I would like a textbox to display the average of all the values in this column. Can't quite figure it out.

Here's the code I have written:

int Counter = 0;
double AverageCalc = 0;

while (Counter < dtaJanuray.Rows.Count)
{
string Average = null;
Average = datagridview.SelectedRows[Counter].Cells[2].Value.ToString();
AverageCalc = AverageCalc + Convert.ToDouble(Average);
Counter++;
}

AverageCalc = AverageCalc / datagridview.Rows.Count;
txtAverage.Text = AverageCalc.ToString();

It loops through once, and then fails at:

Average = datagridview.SelectedRows[Counter].Cells[2].Value.ToString();

When Counter = 1

I'm not really sure what else to try, any advise would be greatly appreciated.
Thanks
Martin

Recommended Answers

try this:

double AverageCalc = 0;
            if (dataGridView1.Rows.Count > 0)
            {
                foreach (DataGridViewRow row in datagridview.Rows)
                {
                    double average;
                    if (double.TryParse(row.Cells[2].Value.ToString(), out average))
                        AverageCalc += average;
                }
                AverageCalc /= datagridview.Rows.Count;
            }
            txtAverage.Text = AverageCalc.ToString();

BTW: You didn't post the error you were getting, only that it is …

Jump to Post

All 2 Replies

try this:

double AverageCalc = 0;
            if (dataGridView1.Rows.Count > 0)
            {
                foreach (DataGridViewRow row in datagridview.Rows)
                {
                    double average;
                    if (double.TryParse(row.Cells[2].Value.ToString(), out average))
                        AverageCalc += average;
                }
                AverageCalc /= datagridview.Rows.Count;
            }
            txtAverage.Text = AverageCalc.ToString();

BTW: You didn't post the error you were getting, only that it is broke

Hey thanks for the reply, just sorted it myself.
just changed:

Average = datagridview.SelectedRows[Counter].Cells[2].Value.ToString();

to:

Average = datagridview.Rows[Counter].Cells[2].Value.ToString();

Thansk all the same :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.