user7135817
user7135817

Reputation:

Adding a row at the bottom of the gridview programmatically in c#?

I would like to add a row at the end of my gridview which has 5 columns as of now. The end row will represent the total of the values of each column. How can i do that ? This is what I tried so far..My row will have the values nominatedquantity, allocatedquantity,volumne,provisionalusd,provisionalkes

using (SqlDataAdapter sda = new SqlDataAdapter())
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@Country", "KENYATEST");

    cmd.Connection = con;
    sda.SelectCommand = cmd;
    using (dt = new DataTable())
    {
      sda.Fill(dt);

      foreach (DataRow dr in dt.Rows)
      {
          allocatedsum += Convert.ToInt32(dr["AllocatedQuantity"]);
          nominatedsum += Convert.ToInt32(dr["NominatedQuantity"]);
          volume += Convert.ToDouble(dr["Volume"]);
          ProvisionalUSD += Convert.ToInt32(dr["ProvisionalUSD"]);
          ProvisionalKES += Convert.ToInt32(dr["ProvisionalKES"]);
      }                       

      GridView1.DataSource = dt;    
      GridView1.DataBind();
    }                                  
}

Upvotes: 0

Views: 1636

Answers (2)

Abhinav
Abhinav

Reputation: 1200

Just add this before you assign dt to your datasource...

 DataRow totalRow = dt.NewRow();
                totalRow["ColumnName"] = "Column Total"; 
                dt.Rows.Add(totalRow);

Upvotes: 0

Prashant Tiwari
Prashant Tiwari

Reputation: 344

You are almost there. All you need to do is create a new row with the total values and add it to the data table, before you populate the gridview with it.

using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Country", "KENYATEST");

            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (dt = new DataTable())
            {

                sda.Fill(dt);

                foreach (DataRow dr in dt.Rows)
                {
                   allocatedsum += Convert.ToInt32(dr["AllocatedQuantity"]);
                   nominatedsum += Convert.ToInt32(dr["NominatedQuantity"]);
                   volume += Convert.ToDouble(dr["Volume"]);
                  ProvisionalUSD += Convert.ToInt32(dr["ProvisionalUSD"]);
                   ProvisionalKES += Convert.ToInt32(dr["ProvisionalKES"]);

                }
                //Create a row for totals over here
                DataRow totalRow = dt.NewRow();
                //Then set the total values inside this row
                totalRow["ColumnName"] = "Column Total"; //for each column
                dt.Rows.Add(totalRow); //finally add the new row to your dource datatable

                GridView1.DataSource = dt;

                GridView1.DataBind();
            }
} }

Upvotes: 1

Related Questions