Ajit N

Ajit N

  • 1.3k
  • 352
  • 68.1k

How to make running total in DataGridView ?

Jan 9 2019 7:30 AM
I want to make running total in datagridview. i tried some code on datagridview's sorted event but i didn't get the expected output.
My Code show's  this type of data in DataGridView-
 
But I expect this output-
 So Help me how can i solve it ?
  1. public void ShowData()  
  2. {  
  3. OleDbCommand cmd = new OleDbCommand("SELECT OB as OpenBalnce,PCB as CloasingBalance,LC as lcno from Balance where LC=" + txtticket.Text + "", con);  
  4.             OleDbDataAdapter da = new OleDbDataAdapter(cmd);  
  5.             DataTable dt = new DataTable();  
  6.             da.Fill(dt);  
  7.   
  8.             OleDbCommand cmd2 = new OleDbCommand("SELECT  amount as Debit,LC as lcno,Narra as Narration,dt as Edate FROM voucher where DrCr='Dr' and FYear='" + cmbyear.Text + "' and LC=" + txtticket.Text + " order by dt ASC", con);  
  9.             OleDbDataAdapter da2 = new OleDbDataAdapter(cmd2);  
  10.             DataTable dt2 = new DataTable();  
  11.             da2.Fill(dt2);  
  12.   
  13.   
  14.             dt2.Merge(dt);  
  15.             dt2.AcceptChanges();  
  16.   
  17.   
  18.             OleDbCommand cmd1 = new OleDbCommand("SELECT  LC as lcno,amount as Credit,Narra as Narration,dt as Edate FROM voucher where DrCr='Cr' and FYear='" + cmbyear.Text + "' and LC=" + txtticket.Text + " order by dt ASC", con);  
  19.             OleDbDataAdapter da1 = new OleDbDataAdapter(cmd1);  
  20.             DataTable dt1 = new DataTable();  
  21.             da1.Fill(dt1);  
  22.   
  23.             dt1.Merge(dt2);  
  24.             dt1.AcceptChanges();  
  25.   
  26.             dataGridView1.DataSource = dt1;  
  27.             dataGridView1.Sort(this.dataGridView1.Columns[3], ListSortDirection.Ascending);  
  28. }  
  29.   
  30. private void dataGridView1_Sorted(object sender, EventArgs e)  
  31.         {  
  32.             for (int i = 1; i < dataGridView1.Rows.Count - 1; i++)  
  33.             {  
  34.                 dataGridView1.Rows[i].Cells[5].Value = Convert.ToInt32(dataGridView1.Rows[i - 1].Cells[5].Value) + Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value) + Convert.ToInt32(dataGridView1.Rows[i].Cells[4].Value);  
  35.                 dataGridView1.Rows[i-1].Cells[6].Value = Convert.ToInt32(dataGridView1.Rows[i-1].Cells[6].Value) + Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value) + Convert.ToInt32(dataGridView1.Rows[i].Cells[4].Value);  
  36.                   
  37.             }  
  38.   
  39.              
  40.         }  

Answers (3)