Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
Hii...

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,
C#
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;
SQL
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.


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

1 solution

C#
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[0]="";
            dr[1] = "Total::";
            dr[2]=count.ToString();
            ds.Tables[0].Rows.Add(dr);
 
Share this answer
 
Comments
Shivani Dash 19-Apr-13 3:24am    
but how to show in grid at perticular that column..?
Sant Osha 19-Apr-13 4:41am    
Dude... you just bind the grid after above iteration, just like..
GridView.DataSource = ds;
GridView.DataBind();
Shivani Dash 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 column..it cums under first column.
Sant Osha 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900