Hi vishalkal,
You can't stop this from happening in regards to keeping the total row always last. So you need to make a function that will calculate the Sum and then display the sum in the last row of DataGridView after binding the data to DataGridView and call the function when ever required.
Check this example. Now please take its reference and correct your code.
Refering the below article i have created the example.
C#
private void Form1_Load(object sender, EventArgs e)
{
BindGrid();
}
private void BindGrid()
{
string constring = @"Data Source=.;Initial Catalog=Northwind;User id = sa;password=pass@123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 5 OrderID,CustomerID,Freight FROM Orders", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
CalculateTotal();
}
}
}
}
}
private void CalculateTotal()
{
decimal total = 0;
for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
total += Convert.ToDecimal(dataGridView1.Rows[i].Cells[2].Value);
}
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = total;
}
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
CalculateTotal();
}
Screenshot