Donate

Prevent DataGridView Last Row From Being Sorted On Column Click

Hello,
You might have a row in the DataGridView typically the last one that computes total and the grid control is unbound to a datasource. And then if a sorting event occurs, you dont' wanna include that row during sort event. So given that your application has a form and a DataGridView control, the code to perform databinding is handled in the Form Load Event.
DataGridViewRow dgRowTotalCount;
DataTable dataTable;

private void Form1_Load(object sender, EventArgs e)
{
 DataTable dt = new DataTable("tblEntTable");
 dt.Columns.Add("ID", typeof(string));
 dt.Columns.Add("Amount", typeof(decimal));
 dt.Rows.Add(new object[] { "1", 100.51 });
 dt.Rows.Add(new object[] { "2", 200.52 });
 dt.Rows.Add(new object[] { "6", 500.24 });
 dt.Rows.Add(new object[] { "8", 1000.11 });
 dt.Rows.Add(new object[] { "4", 400.31 });
 dt.Rows.Add(new object[] { "5", 600.88 });
 dt.Rows.Add(new object[] { "3", 700.11 });
 dt.Rows.Add(new object[] { "7", 700.12 });
 dt.Rows.Add(new object[] { "9", 300.12 });

 foreach (DataRow row in dt.Rows)
 {
  string id = row[0].ToString();
  decimal amount = Convert.ToDecimal(row[1].ToString());
  datagrid.Rows.Add(new object[]{ id, amount });
 }
}
To exclude the totals row from being sorted, the solution is pretty straightforward.  Clone and copy cell content values of the totals row to a DataGridRow object in the Cell Click Event of the grid. Then remove that row from the control.
private void datagrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
 if (e.RowIndex == -1)
 {
  dgRowTotalCount = (DataGridViewRow)datagrid.Rows[((DataGridView)sender).Rows.Count - 1].Clone();
  for (Int32 index = 0; index < ((DataGridView)sender).Rows[((DataGridView)sender).Rows.Count - 1].Cells.Count; index++)
  {
   dgRowTotalCount.Cells[index].Value = ((DataGridView)sender).Rows[((DataGridView)sender).Rows.Count - 1].Cells[index].Value;
  }
  ((DataGridView)sender).Rows.RemoveAt(((DataGridView)sender).Rows.Count - 1);
 }
}
In the sorted event of the grid control, re-insert the row that was cloned and removed from the cell click event.
private void datagrid_Sorted(object sender, EventArgs e)
{
 datagrid.Rows.Insert(((DataGridView)sender).Rows.Count, dgRowTotalCount); 
}

Output (Records sorted by ID in ascending and descending order) Prevent DataGridView Last Row From Being Sorted On Column Click
Prevent DataGridView Last Row From Being Sorted On Column Click
Cheers! :)

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations