WinForms: How to Handle BindingSource Resetting and Preserve State in a DataGridView?
I need some guidance on I'm working through a tutorial and I'm reviewing some code and I've looked through the documentation and I'm still confused about I am currently working on a WinForms application using .NET Framework 4.8, and I'm encountering an issue with a DataGridView that is bound to a BindingSource... My DataGridView seems to be resetting its selection and scroll position whenever I update the underlying data source. I have tried using the `ResetBindings` method on the BindingSource, but it causes the DataGridView to lose its current selection and scroll position, which is a poor user experience in my application. I have set up my BindingSource like this: ```csharp BindingSource bindingSource = new BindingSource(); List<MyDataType> data = GetData(); // This method retrieves the data bindingSource.DataSource = data; myDataGridView.DataSource = bindingSource; ``` To update the data, I modify the original list and call `bindingSource.ResetBindings(false);`. However, I noticed that after the update, the DataGridView resets its selection. I attempted to save the selected index and scroll position before the update by using: ```csharp int selectedIndex = myDataGridView.CurrentCell.RowIndex; int firstDisplayedIndex = myDataGridView.FirstDisplayedScrollingRowIndex; ``` Then, after the update, I tried restoring them with: ```csharp if (selectedIndex >= 0 && selectedIndex < myDataGridView.Rows.Count) { myDataGridView.CurrentCell = myDataGridView.Rows[selectedIndex].Cells[0]; } myDataGridView.FirstDisplayedScrollingRowIndex = firstDisplayedIndex; ``` However, this still does not work correctly in all cases, especially if new rows are added or removed from the data source. I am unsure if I am handling the BindingSource updates correctly or if there is a better way to maintain user state in the DataGridView upon data changes. Any tips or best practices would be greatly appreciated! This is part of a larger API I'm building. Thanks in advance! I'm working with C# in a Docker container on CentOS. What's the best practice here? I'm working in a Windows 11 environment. Thanks, I really appreciate it!