[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Prevent DataGridView from resorting when its DataSource is updated

Posted on 2010-01-06
11
Medium Priority
?
896 Views
Last Modified: 2013-12-17
I have a DataGridView which is bound to an underlying DataTable, which I am able to sort by clicking on the column headers.

However every minute I need to update the DataTable (values in the columns change, but no rows are added/deleted).

When I rebind the DataTable to the DataGridView.DataSource the grid get's unsorted.
(I've tried just updating the DataTable and tried using a BindingSource but the problem seems to be the same)

In the end the only way I was able to do it was to make a note of the last column to be sorted and the direction and then reapply this once the data has been refreshed.

Is there a cleaner way to preserve the sort order when the underlying data is refreshed?
0
Comment
Question by:openshac
  • 5
  • 4
  • 2
11 Comments
 
LVL 10

Expert Comment

by:lof
ID: 26188267
first you need to accept changes on data table

dataTable1.AcceptChanges();

and then you need to refresh the datagrid

dataGridView1.Refresh();
0
 
LVL 6

Author Comment

by:openshac
ID: 26188447
Hi lof,
Thanks for replying, I have tried what you suggested but the DataGridView doesn't seem to update when I call Refresh()
I tried resetting the DataSource with:
    dataGridView1.DataSource = _dt;
but that just unsorts the DataGridView.
Is there something I'm doing wrong?

        DataTable _dt = new DataTable();
        int _counter = 0;

        private void GridSort_Load(object sender, EventArgs e)
        {
            _dt = GetData();
            dataGridView1.DataSource = _dt;

            dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Descending);
            
            _dt = GetData();
            _dt.AcceptChanges();
            dataGridView1.Refresh();
        }

        private DataTable GetData()
        {            
            DataTable dt = new DataTable();
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Number", typeof(Int32));

            for (int i = 0; i < 100; i++)
            {
                dt.Rows.Add(new string[] { "Name" + i.ToString() + " " + _counter.ToString(), i.ToString() });
            }

            _counter++;
            return dt;
        }

Open in new window

0
 
LVL 10

Expert Comment

by:lof
ID: 26188574
The problem occures when you set the DataSource property multiple times. Try this example. I've added one button to add rows one by one after initial load
0
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
LVL 10

Expert Comment

by:lof
ID: 26188577
the code is here
public partial class Form1 : Form
    {
        DataTable _dt;
        int _counter = 0;
        DataView _dv;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _dt = new DataTable();
    

            _dt = GetData();
            _dt.AcceptChanges();
            dataGridView1.DataSource = _dt;
            dataGridView1.Refresh();
            dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Descending);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            object[] objs = { "X", "0" };
            _dt.Rows.Add(objs);
            _dt.AcceptChanges();
            dataGridView1.Refresh();

        }

        void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        private void GridSort_Load(object sender, EventArgs e)
        {
            
        }

        private DataTable GetData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Number", typeof(Int32));

            for (int i = 0; i < 100; i++)
            {
                dt.Rows.Add(new string[] { "Name" + i.ToString() + " " + _counter.ToString(), i.ToString() });
            }

            _counter++;
            return dt;
        }
    }

Open in new window

0
 
LVL 6

Expert Comment

by:aymoon80
ID: 26188668
I did not get your point why you make re-binding? the binding source will fix this problem because you can assigin a Sort expression on it and it will automatically display any changes in the DataSource (your data table) and will sort records according to your sorting expression.
0
 
LVL 10

Expert Comment

by:lof
ID: 26188705
Rebinding was causing problems that is why I said you need to set DataSource only once and than it works.
0
 
LVL 6

Expert Comment

by:aymoon80
ID: 26188799
try to make BindingSource for example call it myBindingSource and assign your datasource of it.

write:
myBindingSource.Sort = " mycolumn1, mycolumn2, mycolumn2 ";
at your FormLoad event


0
 
LVL 6

Author Comment

by:openshac
ID: 26188842
lof,
I get my updated DataTable from the database, I am not adding/removing rows.  However vritually all the data in the table is changing slightly (they are actually time dependant prices).
I don't want to have to modify each row individually when I get a new dataset.
0
 
LVL 6

Accepted Solution

by:
openshac earned 0 total points
ID: 26188876
OK, I've managed to get it working.
I needed to merge the new DataTable with the original DataTable:

DataTable dt = GetData()
((DataTable)dataGridView1.DataSource).Merge(dt);

Open in new window

0
 
LVL 10

Expert Comment

by:lof
ID: 26189161
The reason of the problem was explained and solution - not rebinding or recreating the DataTable object - provided.

By duing Merge you update the table similarily to adding rows manualy in terms that the DataTable object is not recreated.
0
 
LVL 6

Author Comment

by:openshac
ID: 26204332
lof,

You solution involved adding new rows, in the original question it states:
"but no rows are added/deleted"

So the code you kindly provided did not work for the original question as stated.

Thanks any for taking time to help
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses
Course of the Month19 days, 1 hour left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question