Click here to Skip to main content
11,795,568 members (79,317 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C#

I am working on Windows Application and I am stuck in an issue. Suppose have a gridview in which I have to add the value of a particular column.And at the end of the rows it will display the result.Like,

No. Item Rate

1 Pencil 10
2 Box 20

Total: 30

I have written this code,
private void datagridview_CellValueChanged(object sender, DataGridViewCellEventArgs e)
           if (e.ColumnIndex == 2)
               decimal Total = 0;
               for (int i = 0; i < datagridview.Rows.Count; i++)
                   if (Convert.ToString(datagridview.Rows[i].Cells[2].Value) != "")
                       decimal GrossAmnt = Convert.ToDecimal(datagridview.Rows[i].Cells[2].Value.ToString());
                       Total = GrossAmnt + Total;
                       datagridview[2, datagridview.Rows.Count].Value = Total.ToString();


when I execute this it shows me an error;
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Anybody is there please help me to solve this.

Posted 18-Apr-13 19:57pm
Edited 30-Apr-13 21:48pm
Thomas Barbare at 19-Apr-13 2:00am
Your gridView is bind to a database ? or it will be filled by user ?
Shivani Dash at 19-Apr-13 2:06am
no its bind to database.
Thomas Barbare at 19-Apr-13 2:19am
You have to calculate the total and add a row in your datasource with the result in.
Shivani Dash at 19-Apr-13 2:48am the result should show at the end of the gridview row..where the row finished.

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

int count = 0;
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                count = count+ Convert.ToInt32(ds.Tables[0].Rows[i][2].ToString());
            DataRow dr = ds.Tables[0].NewRow();
            dr[1] = "Total::";
Shivani Dash at 19-Apr-13 3:24am
but how to show in grid at perticular that column..?
Sant Osha at 19-Apr-13 4:41am
Dude... you just bind the grid after above iteration, just like..
GridView.DataSource = ds;
Shivani Dash at 19-Apr-13 6:15am
have done sumthg.Actually i can add dt data and can show @ the end of grid bt not under that perticular cums under first column.
Sant Osha at 22-Apr-13 2:43am
then use insert at option

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Maciej Los 340
1 Sergey Alexandrovich Kryukov 316
2 OriginalGriff 285
3 Abhinav S 223
4 KrunalRohit 214
0 OriginalGriff 1,797
1 Maciej Los 1,415
2 KrunalRohit 1,240
3 CPallini 840
4 ppolymorphe 808

Advertise | Privacy | Mobile
Web02 | 2.8.151002.1 | Last Updated 1 May 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100