You must Sign In to post a response.
  • Category: .NET

    Hwot to Calculating The Sum of values from DataGridView

    I am creating windows application using c# 2010, here I am using data grid view for billing purpose, my grid view having 3 columns only(slno, mts, cms),

    How to calculate sum of both cell values, I want below result.

    Slno mts cms
    1 5 3
    2 0 4

    I want = 5.7

    Please give me any one ideas.
  • #767831
    Just you need to loop on each row and collect the required cell values, finally you need to show them in footer row, here is the snippet that will work for you

    int sum = 0;
    for (int i = 0; i < dataGridView1.Rows.Count; ++i)
    sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
    label1.text = sum.ToString();

    in above sample I have taken all rows and store their sum in sum variable, finally I have assign them to a label, you can set it to gridview row also.

    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]

  • #767835
    Hai Boopal,
    For all these type if issues, better to use the RowDataBound event which can handle the event related to individual rows. As this event binds the grid row by row so we can do all the operations which are performing for each of the row.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    int count = 0;
    int col1Value = Convert.ToInt32(e.Row.Cells[1].Text); // for first column value
    int col2Value = Convert.ToInt32(e.Row.Cells[2].Text); // for second column value
    count += col1Value + col2Value;
    label1.Text = count.ToString();

    Hope it will be helpful to you.

    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)

  • #767840

    On ItemDataBound event of datagridview you can add the cell values and show it in your result label.

    int cnt=0;
    protected void dgv_OnItemDataBound(object sender, DataGridItemEventArgs e)
    if(e.Item.ItemType == Listitemtype.Item || e.Item.ItemType == Listitemtype.AlternateItem )
    cnt + = Convert.ToInt32(e.Item.Cells[2].Text);

    Hope this helps you...

    Give respect to your work, Instead of trying to impress your boss.

    Blog :

  • Sign In to post your comments