简体   繁体   中英

Add new row to sorted datagridview c#

I'm trying to add a new row to my datagridview

DataRow dr = new dt.NewRow();
dt.Rows.InsertAt(dr,5);

And a few lines above I have this line of code

Datagridview1.Sort(datagridview1.Columns[6],ListSortDirection.Ascending);

The problem is that my datagridview sorted again after im adding new row. And my row appearing at row 1 instmi of row 5

What can i do to fix it?

Ok I will explain you my final target. I have a datagridview that sorted like i said. And i want to add a summery row and i need it to be at the end of the datagridview. How can i do it?

It is the way it's supposed to be. You told the grid to sort rows based on that column. So if you want to show rows based on any other preference, tell that to the grid.

  • If you need the rows to be sorted only at first load, just load them sorted from data store and then don't set any sort for grid. This way you can insert your summary row at the end.
  • If you want to let the user also sort the grid while having a summary row, you can handle sorting of grid yourself.

Example

I personally prefer to create a report to satisfy such requirement. Also the summary can be shown in some text boxes under the grid.

But for cases that you really need to do a task like this, here is an example that shows you how to let the user sort grid, while you have a summary row. It sorts the grid without changing the summary row position.

Here is the form load event. We load data, set data source of grid and also set columns sort mode to Programmatic :

DataTable originalData;
private void Form1_Load(object sender, EventArgs e)
{
    GetData();
    SetDataSource();

    //Set all columns sort mode to Programmatic
    this.dataGridView1.Columns.Cast<DataGridViewColumn>().ToList()
        .ForEach(c => { c.SortMode = DataGridViewColumnSortMode.Programmatic; });

    this.dataGridView1.ColumnHeaderMouseClick += dataGridView1_ColumnHeaderMouseClick;
}

Handle click event of column headers and sort data. Read comments of code:

void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    var grid = (DataGridView)sender;

    //Removes sort glyph 
    this.dataGridView1.Columns.Cast<DataGridViewColumn>()
        .Except(new[] { grid.Columns[e.ColumnIndex] }).ToList()
        .ForEach(c => { c.HeaderCell.SortGlyphDirection = SortOrder.None; });

    //Sort descending if currently sorted ascending
    if (grid.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection == SortOrder.Ascending)
    {
        originalData.DefaultView.Sort = 
            string.Format("{0} DESC", grid.Columns[e.ColumnIndex].DataPropertyName);
        SetDataSource();
        grid.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = SortOrder.Descending;
    }
    //Sort ascending if currently sorted ascending or not sorted
    else
    {
        originalData.DefaultView.Sort = 
            string.Format("{0} ASC", grid.Columns[e.ColumnIndex].DataPropertyName);
        SetDataSource();
        grid.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = SortOrder.Ascending;
    }
}

Here is the method to set data source of grid. Here you should add your summary column to the copy of original data table:

void SetDataSource()
{
    //Copies rows of oroginal data table to a new one based on ordering
    //Then adds a summary row
    //Sets the result as DataSource of grid
    var copy = originalData.DefaultView.ToTable();
    copy.Rows.Add("", originalData.AsEnumerable().Sum(x => x.Field<int>("Value")));
    this.dataGridView1.DataSource = copy;
}

Here is the method to load data. You load data from database and I just add some data to test:

void GetData()
{
    //You load data from database and this data is just for test
    originalData = new DataTable();
    originalData.Columns.Add("Name", typeof(string));
    originalData.Columns.Add("Value", typeof(int));
    originalData.Rows.Add("a", 10);
    originalData.Rows.Add("b", 30);
    originalData.Rows.Add("c", 20);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM